Python 如果是函数还是分组
对熊猫来说是新的。我最初写这段代码是为了读取.csv,现在我写的是读取.xlsx文件。无论如何,我之前使用了if函数来读取if Valid Part==“YES”,然后。。。。。遵循代码的其余部分 现在我正在使用熊猫,我一直在测试groupby以实现我的计数,但还没有完全弄清楚 在这个示例中,如果有效部分=='Yes'和Appl Req=='Yes'给我计数,我会查看 任何建议都将不胜感激Python 如果是函数还是分组,python,pandas,Python,Pandas,对熊猫来说是新的。我最初写这段代码是为了读取.csv,现在我写的是读取.xlsx文件。无论如何,我之前使用了if函数来读取if Valid Part==“YES”,然后。。。。。遵循代码的其余部分 现在我正在使用熊猫,我一直在测试groupby以实现我的计数,但还没有完全弄清楚 在这个示例中,如果有效部分=='Yes'和Appl Req=='Yes'给我计数,我会查看 任何建议都将不胜感激 import pandas as pd df = pd.read_excel('IMPORT.xlsx'
import pandas as pd
df = pd.read_excel('IMPORT.xlsx')
app_req = df.groupby(['Valid Part', 'Appl Req']).count()
print(app_req)
数据样本
我认为您需要先按或过滤,然后按以下方式聚合: 编辑: 样本:
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=读取我的excel文档,这是否同样有效?当然,没有问题。但是尝试3
if数字和'3'
if字符串。
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