2017-10-20 91 views
0

我想在使用熊貓的csv文件中實現簡單的投票分數。基本上,如果dataframe ['C'] == Active和dataframe ['Count'] == 0,那麼dataframe ['Combo'] == 0.如果dataframe ['C'] == Active和dataframe [''計數'] == 1;然後dataframe ['Combo'] == 1.如果dataframe ['C'] == Active和dataframe ['Count'] == 2;然後dataframe ['Combo'] == 2等等。忽略熊貓中的重複值

這是我的數據框:

A  B   C   Count Combo 
Ptn1 Lig1  Inactive 0  
Ptn1 Lig1  Inactive 1  
Ptn1 Lig1  Active  2  2 
Ptn2 Lig2  Active  0  0 
Ptn2 Lig2  Inactive 1  
Ptn3 Lig3  Active  0  0 
Ptn3 Lig3  Inactive 1  
Ptn3 Lig3  Inactive 2  
Ptn3 Lig3  Inactive 3  
Ptn3 Lig3  Active  4  3 

這是到目前爲止我的代碼爲清楚:

import pandas as pd 
df = pd.read_csv('affinity.csv') 
VOTE = 0 
df['Combo'] = '' 
df.loc[(df['Classification] == 'Active') & (df['Count'] == 0), 'Combo'] = VOTE 
df.loc[(df['Classification] == 'Active') & (df['Count'] == 1), 'Combo'] = VOTE + 1 
df.loc[(df['Classification] == 'Active') & (df['Count'] == 2), 'Combo'] = VOTE + 2 
df.loc[(df['Classification] == 'Active') & (df['Count'] > 3), 'Combo'] = VOTE + 3 

我的代碼能夠正確地做到這一點。但是,Ptn3-Lig3對有兩個「有效」值;一個在dataframe ['Count'] = 0,另一個在dataframe ['Count'] = 4. 有沒有辦法忽略第二個值(即只考慮最小的數據幀['Count']值)並添加相應的數字到數據框['組合']? 我知道pandas.DataFrame.drop_duplicates()可能是一種只選擇唯一值的方法,但它會非常好,避免刪除任何行。

回答

1

你可以做一個groupby + apply

def foo(x): 
    m = x['C'].eq('Active') 
    if m.any(): 
     return pd.Series(np.where(m, x.loc[m, 'Count'].head(1), np.nan)) 
    else: 
     return pd.Series([np.nan] * len(x)) 

df['Combo'] = df.groupby(['A', 'B'], group_keys=False).apply(foo).values 
print(df) 

     A  B   C Count Combo 
0 Ptn1 Lig1 Inactive  0  
1 Ptn1 Lig1 Inactive  1  
2 Ptn1 Lig1 Active  2  2 
3 Ptn2 Lig2 Active  0  0 
4 Ptn2 Lig2 Inactive  1  
5 Ptn3 Lig3 Active  0  0 
6 Ptn3 Lig3 Inactive  1  
7 Ptn3 Lig3 Inactive  2  
8 Ptn3 Lig3 Inactive  3  
9 Ptn3 Lig3 Active  4  0 

另一種選擇與groupby + merge

df = df.groupby(['A', 'B', 'C'])['C', 'Count']\ 
     .apply(lambda x: x['Count'].values[0] if x['C'].eq('Active').any() else np.nan)\ 
     .reset_index(name='Combo').fillna('').merge(df) 
print(df) 

     A  B   C Combo Count 
0 Ptn1 Lig1 Active  2  2 
1 Ptn1 Lig1 Inactive   0 
2 Ptn1 Lig1 Inactive   1 
3 Ptn2 Lig2 Active  0  0 
4 Ptn2 Lig2 Inactive   1 
5 Ptn3 Lig3 Active  0  0 
6 Ptn3 Lig3 Active  0  4 
7 Ptn3 Lig3 Inactive   1 
8 Ptn3 Lig3 Inactive   2 
9 Ptn3 Lig3 Inactive   3 

注意,這最終排序的羣體。

+0

謝謝。這對於這個示例數據框很有用,但是當我嘗試將它應用於真實事物時,它引發了一個錯誤:return pd.Series(np.where(m,x.loc [m,'Count']。head(1), ')) ValueError:操作數無法與形狀(5,)(0,)()一起廣播。你能解釋一下這個功能在做什麼嗎?我對python和熊貓非常陌生。 –

+1

@MarcosSantana見編輯?我想我可能已經理解了這個問題。 –

+0

哦。剛剛看到它。現在該功能正在運行。但是我仍然得到Ptn3-Lig3對的兩個值。如果不是通過該函數,是否有辦法將第二個值更改爲NaN或其他東西?再次感謝您的功能! –