Here's a pd.Dataframe.
index date state
one 2000 Ohio
two 2012 Ohio
And I want df['state'] = 'California' where df['date'] == 2000 and df.index == one
.
How can I do this?
Thanks for the help!
df.loc[df.state=='California' and df.date==2000 and df.index=='one', :]
Use if index
is not column set new values by DataFrame.loc
with conditions:
print (df.columns)
Index(['date', 'state'], dtype='object')
df.loc[(df['date'] == 2000) & (df.index == 'one'), 'state'] = 'California'
print (df)
date state
index
one 2000 California
two 2012 Ohio
If index is column select it by []
:
print (df.columns)
Index(['index', 'date', 'state'], dtype='object')
df.loc[(df['date'] == 2000) & (df['index'] == 'one'), 'state'] = 'California'
print (df)
index date state
0 one 2000 California
1 two 2012 Ohio
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.