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

例如我有简单的 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),但我懒得修复它。为读者练习。 :^)

https://stackoverflow.com/questions/15315452/

相关文章:

python - 使用 Python 向 RESTful API 发出请求

linux - 如何就地对文件进行排序?

linux - 如何永久清除 linux/ubuntu 终端或 bash 中的所有历史记录?

linux - 如何在bash中创建仅包含十六进制字符而不包含空格的文件的十六进制转储?

python - `ValueError: cannot reindex from a duplic

python - 如何在 Django 中的 CharField 上添加占位符?

linux - 确定 yum 软件包安装到的路径

linux - 如何在 Linux 上获得整体 CPU 使用率(例如 57%)

python - 如何使用 python/numpy 计算百分位数?

python - 如何从 python 代码调用 shell 脚本?