python - Pandas If 函数或 groupby

标签 python pandas

Pandas 新手。我最初编写此代码是为了读取 .csv,现在我编写此代码是为了读取 .xlsx 文件。无论如何,我之前使用 if 函数来读取 if Valid Part == 'YES' then ..... 遵循其余代码。

现在我正在使用 Pandas,我一直在测试 groupby 来实现我的计数,但还没有完全弄清楚。

我正在查看这个示例,如果 Valid Part == 'Yes' 且 Appl Req == 'Yes' 给我计数。

非常感谢任何建议。

import pandas as pd

df = pd.read_excel('IMPORT.xlsx')

app_req = df.groupby(['Valid Part', 'Appl Req']).count()

print(app_req)

数据示例

enter image description here

最佳答案

我认为您需要按 boolean indexing 进行过滤或query首先,然后按 size 聚合:

df = df[(df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')]
app_req = df.groupby(['Valid Part', 'Appl Req']).size()

What is the difference between size and count in pandas?

编辑:

示例:

np.random.seed(100)
N = 10
df = pd.DataFrame(np.random.choice(['Yes','No'], size=(N,3)), 
                  columns=['Valid Part', 'Appl Req', 'A'])
print (df)
   Valid Part Appl Req    A
0         Yes      Yes   No
1          No       No   No
2         Yes      Yes  Yes
3         Yes      Yes   No
4         Yes      Yes  Yes
5         Yes       No  Yes
6         Yes       No  Yes
7          No      Yes  Yes
8         Yes       No   No
9          No      Yes  Yes

看来您只需要 True 值的总和:

print ((df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes'))
0     True
1    False
2     True
3     True
4     True
5    False
6    False
7    False
8    False
9    False
dtype: bool

app_req = ((df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')).sum()
print (app_req)
4
<小时/>
df = df[(df['Valid Part'] == 'Yes') & (df['Appl Req'] == 'Yes')]
app_req = df.groupby(['Valid Part', 'Appl Req']).size().reset_index(name='COUNT')
print (app_req)
  Valid Part Appl Req  COUNT
0        Yes      Yes      4

关于python - Pandas If 函数或 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976981/

相关文章:

python - 在列表中连接后获得最大数量

python - 为什么 OrderedDict 的值不相等?

python - celery : understanding the big picture

python - 透视数据框 reshape 并查找前一天计数,但第 0 天值为 0

python - 散点图 x 轴刻度标签未显示

python - 是否有一种有效的方法来检查列是否具有混合 dtypes?

python - 如何使用列名称中的空格进行 SOQL 查询?

python - 2D bin (x,y) 并计算 10 个最深数据点 (z) 的平均值 (c)

python - 实现 cdc 但在 Python Pandas 中出现值错误

python - 具有 12 个输入和输出节点且无嵌入的 LSTM