摘要:这不起作用:
df[df.key==1]['D'] = 1
但这确实:
df.D[df.key==1] = 1
为什么?
再生产:
In [1]: import pandas as pd
In [2]: from numpy.random import randn
In [4]: df = pd.DataFrame(randn(6,3),columns=list('ABC'))
In [5]: df
Out[5]:
A B C
0 1.438161 -0.210454 -1.983704
1 -0.283780 -0.371773 0.017580
2 0.552564 -0.610548 0.257276
3 1.931332 0.649179 -1.349062
4 1.656010 -1.373263 1.333079
5 0.944862 -0.657849 1.526811
In [6]: df['D']=0.0
In [7]: df['key']=3*[1]+3*[2]
In [8]: df
Out[8]:
A B C D key
0 1.438161 -0.210454 -1.983704 0 1
1 -0.283780 -0.371773 0.017580 0 1
2 0.552564 -0.610548 0.257276 0 1
3 1.931332 0.649179 -1.349062 0 2
4 1.656010 -1.373263 1.333079 0 2
5 0.944862 -0.657849 1.526811 0 2
这不起作用:
In [9]: df[df.key==1]['D'] = 1
In [10]: df
Out[10]:
A B C D key
0 1.438161 -0.210454 -1.983704 0 1
1 -0.283780 -0.371773 0.017580 0 1
2 0.552564 -0.610548 0.257276 0 1
3 1.931332 0.649179 -1.349062 0 2
4 1.656010 -1.373263 1.333079 0 2
5 0.944862 -0.657849 1.526811 0 2
但这确实:
In [11]: df.D[df.key==1] = 3.4
In [12]: df
Out[12]:
A B C D key
0 1.438161 -0.210454 -1.983704 3.4 1
1 -0.283780 -0.371773 0.017580 3.4 1
2 0.552564 -0.610548 0.257276 3.4 1
3 1.931332 0.649179 -1.349062 0.0 2
4 1.656010 -1.373263 1.333079 0.0 2
5 0.944862 -0.657849 1.526811 0.0 2
我的问题是:
为什么只有第二种方式有效?我似乎看不出选择/索引逻辑有什么不同。
版本是 0.10.0
编辑:这不应该再这样做了。从 0.11 版开始,有
.loc
. 见这里: http: //pandas.pydata.org/pandas-docs/stable/indexing.html