2017-07-07 68 views
1

熊貓的新功能。我有這個代碼最初寫入讀取.csv,現在我正在寫入讀取.xlsx文件。無論如何,我使用如果函數之前閱讀如果有效部分=='是'然後.....按照其餘的代碼。熊貓如果功能或groupby

現在我正在使用熊貓,我一直在測試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

回答

1

我想你需要通過過濾器或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 
+1

缺少'DF ['? –

+0

如果我已經使用df =來讀取我的excel文檔,這是否也能工作? –

+0

是的,它對你的數據很好。 – jezrael