2016-07-01 75 views
1

一個SeriesGroupBy對象我有一個數據幀df1用途適用於在條件滿足

df1.head() = 

      id  ret  eff 
    1469 2300 -0.010879 4480.0 
    328 2300 -0.000692 -4074.0 
    1376 2300 -0.009551 4350.0 
    2110 2300 -0.014013 5335.0 
    849 2300 -0.286490 -9460.0 

我想創建一個包含列df1['eff']的標準化值的新列。
換句話說,我想組df1['eff']df1['id'],通過根據是否df1['eff'] > 0mnmxdf1['eff']的每個值尋找最大值(mx = df1['eff'].max())和最小值(mn = df2['eff'].min()),除以成對的方式或df1['eff']< 0

我寫的代碼如下:

df1['normd'] = df1.groupby('id')['eff'].apply(lambda x: x/x.max() if x > 0 else x/x.min()) 

然而蟒蛇引發以下錯誤:

*** ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), 
a.item(), a.any() or a.all(). 

由於df1.groupby('id')['eff']SeriesGroupBy Object,我決定使用map()。 但蟒蛇再次引發以下錯誤:

*** AttributeError: Cannot access callable attribute 'map' of 'SeriesGroupBy' ob 
jects, try using the 'apply' method 

提前非常感謝。

+0

的問題是,目前還不清楚,你用'DF1是什麼意思[「EFF」]> 0' ,即使用簡單的英語。你是說你知道一個組裏的所有'eff'值都有相同的符號嗎? – IanS

+0

當然,當你申請時,'x'是一個系列,所以熊貓不知道'x> 0'是什麼。我也不會,因此我的問題;) – IanS

+0

我認爲'map()'是一個成對函數。因此,通過使用'df1 ['eff']> 0'',我意在成對分析列df1 ['eff']'中的每個值是否爲正數。 –

回答

3

您可以使用自定義功能f,在哪裏可以輕鬆添加print。所以xSeries,你需要比較每組numpy.where。輸出爲numpy array,你需要將其轉換爲Series

def f(x): 
    #print (x) 
    #print (x/x.max()) 
    #print (x/x.min()) 
    return pd.Series(np.where(x>0, x/x.max(), x/x.min()), index=x.index) 


df1['normd'] = df1.groupby('id')['eff'].apply(f) 
print (df1) 
     id  ret  eff  normd 
1469 2300 -0.010879 4480.0 0.839738 
328 2300 -0.000692 -4074.0 0.430655 
1376 2300 -0.009551 4350.0 0.815370 
2110 2300 -0.014013 5335.0 1.000000 
849 2300 -0.286490 -9460.0 1.000000 

什麼是一樣的:

df1['normd'] = df1.groupby('id')['eff'] 
        .apply(lambda x: pd.Series(np.where(x>0, 
                 x/x.max(), 
                 x/x.min()), index=x.index)) 
print (df1) 
     id  ret  eff  normd 
1469 2300 -0.010879 4480.0 0.839738 
328 2300 -0.000692 -4074.0 0.430655 
1376 2300 -0.009551 4350.0 0.815370 
2110 2300 -0.014013 5335.0 1.000000 
849 2300 -0.286490 -9460.0 1.000000 
+0

它的工作原理!非常感謝! –