This code should return a new column called orc_4 with the value of 1 if the value of the row in df['indictment_charges'] contains 2907.04 or 0 if not.

Instead it is returning all 0's

for index, item in enumerate(df.indictment_charges):
    s = '2907.04' 
    if s in str(item):
        df['orc_4'] = np.where(item == s, 1, 0)

Why won't it return 1?

Example output for df.indictment_charges:


You are first checking if the item contains the string, but then in np.where you are checking if the values are equal (item == s), which is obviously different. In addition, you set the whole column equal to the value from np.where (and overwriting it after each row), which results in the whole column getting the value based on the final row of the dataframe. To avoid looping over the rows (which is relatively quite slow) you can use pandas.Series.str.contains to check if a string contains a certain value like this:

df["orc_4"] = np.where(df["indictment_charges"].str.contains("2907.04"), 1, 0)
  • $\begingroup$ Decently slow running over 73,000 rows, but it got the job done thank you for the quick answer. $\endgroup$ Feb 4 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.