Python - Pandas DataFrame - Replace All Values in A Column, Based On Condition - Stack Overflow
Python - Pandas DataFrame - Replace All Values in A Column, Based On Condition - Stack Overflow
I want to select all values from the 'First Season' column and replace those that are over 1990 by 1. In this example, only Baltimore Ravens would have the
1996 replaced by 1 (keeping the rest of the data intact).
But, it replaces all the values in that row by 1, and not just the values in the 'First Season' column.
1 Answer
In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df
Out[41]:
Team First Season Total Games
0 Dallas Cowboys 1960 894
1 Chicago Bears 1920 1357
2 Green Bay Packers 1921 1339
3 Miami Dolphins 1966 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 1950 1003
You can check the docs and also the 10 minutes to pandas which shows the semantics
EDIT
If you want to generate a boolean indicator then you can just use the boolean condition to generate a
boolean Series and cast the dtype to int this will convert True and False to 1 and 0 respectively:
In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df
Out[43]:
Team First Season Total Games
0 Dallas Cowboys 0 894
1 Chicago Bears 0 1357
2 Green Bay Packers 0 1339
3 Miami Dolphins 0 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 0 1003
https://stackoverflow.com/questions/31511997/pandas-dataframe-replace-all-values-in-a-column-based-on-condition 1/2
02/03/2018 python - Pandas DataFrame: replace all values in a column, based on condition - Stack Overflow
Worked great! Isn't it possible to impose multiple transformations? df.loc[df['First Season'] > 1990,
'First Season'] = 1 df.loc[df['First Season'] < 1990, 'First Season'] = 0 makes all the values in
that column return 0 – ichimok Jul 20 '15 at 8:46
You can use a trick df['First Season'] = (df['First Season'] > 1990).astype(int) this creates a
boolean Series and casting to int converts True and False to 1 and 0 respectively – EdChum Jul 20 '15
at 8:49
Join Stack Overflow to learn, share knowledge, and build your career. Email Sign Up OR SIGN IN WITH Google Facebook
https://stackoverflow.com/questions/31511997/pandas-dataframe-replace-all-values-in-a-column-based-on-condition 2/2