Pandas:如何基于列值选择行

175 阅读1分钟

你可以使用以下方法之一,根据列值在pandas DataFrame中选择行。

方法1:选择列值等于特定值的行

df.loc[df['col1'] == value]

方法2:选择列值在数值列表中的行

df.loc[df['col1'].isin([value1, value2, value3, ...])]

方法3:基于多列条件选择行

df.loc[(df['col1'] == value) & (df['col2'] < value)]

下面的例子显示了如何用下面的pandas数据框架来使用每个方法:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   'points': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
                   'blocks': [4, 7, 7, 6, 5, 8, 9, 10]})

#view DataFrame
df

	team	points	rebounds blocks
0	A	5	11	 4
1	A	7	8	 7
2	B	7	10	 7
3	B	9	6	 6
4	B	12	6	 5
5	C	9	5	 8
6	C	9	9	 9
7	C	4	12	 10

方法1:选择列值等于特定值的行

下面的代码显示了如何选择DataFrame中 "points "列等于7的每一行:

#select rows where 'points' column is equal to 7
df.loc[df['points'] == 7]

	team	points	rebounds blocks
1	A	7	8	 7
2	B	7	10	 7

方法2:选择列值在数值列表中的行

下面的代码显示了如何在DataFrame中选择 "积分 "列等于7、9或12的每一行:

#select rows where 'points' column is equal to 7
df.loc[df['points'].isin([7, 9, 12])]

        team	points	rebounds blocks
1	A	7	8	 7
2	B	7	10	 7
3	B	9	6	 6
4	B	12	6	 5
5	C	9	5	 8
6	C	9	9	 9

方法3:基于多列条件选择行

下面的代码显示了如何在DataFrame中选择 "团队 "列等于 "B "且 "积分 "列大于8的每一行:

#select rows where 'team' is equal to 'B' and points is greater than 8
df.loc[(df['team'] == 'B') & (df['points'] > 8)]

	team	points	rebounds blocks
3	B	9	6	 6
4	B	12	6	 5

注意,只有球队等于'B'和'积分'大于8的两行被返回。

其他资源

下面的教程解释了如何在pandas中执行其他常见操作:

如何在Pandas中通过索引选择行
如何在Pandas中选择唯一行
如何在Pandas中选择值出现在任何列的行