1

I have a pandas dataframe. There are about 50 columns and 50000 rows. If one colums has a row that

str.contains('certain response')

I want to change the other column response to

'NA'

How would I do that?

o-90
  • 17,045
  • 10
  • 39
  • 63
Eric Kim
  • 13
  • 3
  • Sorry, I dont understand your question: Do mean the following? If the value of one column contains "certain response" you want to change the value of another column to "NA" (in the same row). – nCessity Jun 21 '17 at 19:30
  • Yes! I have this so far, it isn't working. df = df.loc[df.column1.contains('certain response'), 'column 2'] = 'NaN' – Eric Kim Jun 21 '17 at 19:40
  • 1
    Possible duplicate of [Python PANDAS, change one value based on another value](https://stackoverflow.com/questions/19226488/python-pandas-change-one-value-based-on-another-value) – o-90 Jun 21 '17 at 19:41

1 Answers1

0

I believe you need str.contains for condition and if need replace by NaN use np.nan:

df.loc[df.column1.str.contains('certain response'), 'column 2'] = np.nan

Or use mask, if True get NaNs:

df['column 2'] = df['column 2'].mask(df.column1.str.contains('certain response'))

Sample:

df = pd.DataFrame({'column1':['certain response','certain response 2','aaa'],
                   'column 2':[2,3,4]})
df['column 2'] = df['column 2'].mask(df.column1.str.contains('certain response'))
print (df)
  column 2             column1
0       NaN    certain response
1       NaN  certain response 2
2       4.0                 aaa
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252