python - 从 pandas.DataFrame 中选择复杂的标准

标签 python pandas

例如我有简单的 DF:

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)]})

我能否使用 Pandas 的方法和习语从“A”中选择“B”对应值大于 50 和“C”不等于 900 的值?

最佳答案

当然!设置:

>>> 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

我们可以应用列操作并获取 bool 系列对象:

>>> 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

[更新,切换到新样式的.loc]:

然后我们可以使用这些索引到对象中。对于读取访问,您可以链接索引:

>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2    5
3    8
Name: A, dtype: int64

但是您可能会因为 View 和副本之间的差异而陷入麻烦,这样做是为了写访问权。你可以使用 .loc 代替:

>>> 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

请注意,我不小心输入了 == 900 而不是 != 900~(df["C"] == 900),但我懒得修复它。为读者练习。 :^)

关于python - 从 pandas.DataFrame 中选择复杂的标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315452/

相关文章:

python - SSL 上的 MITM 代理卡在客户端的 wrap_socket 上

python - 我如何迭代地创建一堆 JSON 类型的字符串文字?

python - 如何获得函数体?

python - 选择线上方/下方的点

python - 如何向散点图添加图例?

python - virtualenv 是如何工作的?

python - 使用描述符访问变量而不是将此变量与实例中的目标绑定(bind)

python - 在列中查找与其他数据帧列中的任何其他值匹配的行号

python - 使用字典作为键划分两个 Pandas DataFrame

python - 将函数应用于 GroupBy pandas 数据框时出现 iterrows 错误