简体   繁体   English

如何切片pandas.DataFrame?

[英]How to slice a pandas.DataFrame?

Here's a pd.Dataframe.这是一个 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 .我想要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:如果index不是DataFrame.loc列设置新值, DataFrame.loc使用条件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM