3

I want to fill N.A. values in a specific column if a condition is met in another column to only replace this single class of N.A. values with an imputed / replacement value.

E.g. I want to perform: if column1 = 'value1' AND column2 = N.A fillna_in_column2 with value 'replacementvalue'

How do I achieve this in pandas?

Trying to do this via dataframe[dataframe['firstColumn'] == 'value1'].fillna({'column2':'replacementValue'} does not work as the length of the overall records is modified. So far I could not get an inplace modification to work.

Georg Heiler
  • 16,916
  • 36
  • 162
  • 292

2 Answers2

4
df.loc[(df['col1']==val1) & (df['col2'].isnull()), 'col2'] = replacement_value
ayhan
  • 70,170
  • 20
  • 182
  • 203
1

You can try this:

cond1 = df['column1'] == value1
cond2 = np.isnan(df['column2'])

df['column2'][cond1 & cond2] = replacement_value
gabra
  • 9,484
  • 4
  • 29
  • 45