从 pandas.DataFrame 中选择复杂的标准 [英] Selecting with complex criteria from pandas.DataFrame
问题描述
例如我有简单的 DF:
将pandas导入为pd来自随机导入 randintdf = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],'B': [randint(1, 9)*10 for x in xrange(10)],'C': [randint(1, 9)*100 for x in xrange(10)]})
我可以使用 Pandas 的方法和习惯用法从 'A' 中选择值,其中 'B' 的对应值将大于 50,而 'C' 的对应值不等于 900?
好的!设置:
<预><代码>>>>将熊猫导入为 pd>>>来自随机导入 randint>>>df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],'B': [randint(1, 9)*10 for x in range(10)],'C': [randint(1, 9)*100 for x in range(10)]})>>>df乙丙0 9 40 3001 9 70 7002 5 70 9003 8 80 9004 7 50 2005 9 30 9006 2 80 7007 2 80 4008 5 80 3009 7 70 800我们可以应用列操作并获得布尔系列对象:
<预><代码>>>>df["B"] >500 错误1 真2 真3 真4 错误5 错误6 真7 真8 真9 真姓名:乙>>>(df["B"] > 50) &(df["C"] == 900)0 错误1 错误2 真3 真4 错误5 错误6 错误7 错误8 错误9 错误[更新,切换到新样式.loc
]:
然后我们可以使用这些来索引对象.对于读取访问,您可以链接索引:
<预><代码>>>>df["A"][(df["B"] > 50) &(df["C"] == 900)]2 53 8名称:A,数据类型:int64但是由于视图和副本之间的差异,您可能会遇到麻烦,这样做是为了写访问.您可以使用 .loc
代替:
请注意,我不小心输入了 == 900
而不是 != 900
,或者 ~(df["C"] == 900)
,但我懒得修.为读者练习.:^)
For example I have simple DF:
import pandas as pd
from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
'B': [randint(1, 9)*10 for x in xrange(10)],
'C': [randint(1, 9)*100 for x in xrange(10)]})
Can I select values from 'A' for which corresponding values for 'B' will be greater than 50, and for 'C' - not equal 900, using methods and idioms of Pandas?
Sure! Setup:
>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
'B': [randint(1, 9)*10 for x in range(10)],
'C': [randint(1, 9)*100 for x in range(10)]})
>>> df
A B C
0 9 40 300
1 9 70 700
2 5 70 900
3 8 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
We can apply column operations and get boolean Series objects:
>>> df["B"] > 50
0 False
1 True
2 True
3 True
4 False
5 False
6 True
7 True
8 True
9 True
Name: B
>>> (df["B"] > 50) & (df["C"] == 900)
0 False
1 False
2 True
3 True
4 False
5 False
6 False
7 False
8 False
9 False
[Update, to switch to new-style .loc
]:
And then we can use these to index into the object. For read access, you can chain indices:
>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2 5
3 8
Name: A, dtype: int64
but you can get yourself into trouble because of the difference between a view and a copy doing this for write access. You can use .loc
instead:
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2 5
3 8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
A B C
0 9 40 300
1 9 70 700
2 5000 70 900
3 8000 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
Note that I accidentally typed == 900
and not != 900
, or ~(df["C"] == 900)
, but I'm too lazy to fix it. Exercise for the reader. :^)
这篇关于从 pandas.DataFrame 中选择复杂的标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!