Pandas:如何用条件来计算列中的值

143 阅读2分钟

你可以使用以下方法来计算带有特定条件的pandas DataFrame列中的值的数量。

方法1:计算有条件的一列中的值

len(df[df['col1']=='value1'])

方法2:用条件计算多列中的值

len(df[(df['col1']=='value1') & (df['col2']=='value2')])

下面的例子展示了如何在实践中使用每一种方法,包括以下pandas DataFrame。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'pos': ['Gu', 'Fo', 'Fo', 'Fo', 'Gu', 'Gu', 'Fo', 'Fo'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28]})

#view DataFrame
print(df)

  team pos  points
0    A  Gu      18
1    A  Fo      22
2    A  Fo      19
3    A  Fo      14
4    B  Gu      14
5    B  Gu      11
6    B  Fo      20
7    B  Fo      28

例子1:用条件计算一列中的值

下面的代码显示了如何计算团队列中值等于'A'的数值的数量。

#count number of values in team column where value is equal to 'A'
len(df[df['team']=='A'])

4

我们可以看到,在团队列中有4个值等于'A'。

例2:用条件计算多列中的值

下面的代码显示了如何计算DataFrame中团队列等于'B'且位置列等于'Gu'的行的数量。

#count rows where team is 'B' and pos is 'Gu'
len(df[(df['team']=='B') & (df['pos']=='Gu')])

2

我们可以看到,DataFrame中有2行同时满足这些条件。

我们可以使用类似的语法来计算满足任何数量条件的行的数量。

例如,下面的代码显示了如何计算满足三个条件的行的数量。

  • team等于'B'
  • 位置等于'Gu
  • 积分大于12
#count rows where team is 'B' and pos is 'Gu' and points > 15
len(df[(df['team']=='B') & (df['pos']=='Gu') & (df['points']>12)])

1

我们可以看到,DataFrame中只有1行满足所有这三个条件。