0

Question is how can I set value to the specific rows of just created column? I can do

df['New_column'] = np.nan
df['New_columns][df['Old_column'] > 20] = SPECIFIC_VALUE

But I cannot do it without predefining new column as nan:

df['New_columns][df['Old_column'] > 20] = SPECIFIC_VALUE ### That gives me error

Is there way to do such operation without "predefining"

  • Does this answer your question? [Set value for particular cell in pandas DataFrame using index](https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index) – Mykola Zotko Jan 24 '20 at 11:30

1 Answers1

1

Use DataFrame.loc:

df.loc[df['Old_column'] > 20, 'New_columns'] = SPECIFIC_VALUE

If want set 2 new values use numpy.where:

df['New_Columns'] = np.where(df['Old_column'] > 20,SPECIFIC_VALUE, np.nan)
jezrael
  • 629,482
  • 62
  • 918
  • 895