![](/img/trans.png)
[英]GroupBy a custom lambda function (using strings) in pandas
[英]Data Error Using function and groupby to union strings in pandas dataframe
我有以下結構的數據框:
mydf:
Entry Address ShortOrdDesc
0 988 Fake Address 1 SC_M_W_3_1
1 989 Fake Address 2 SC_M_W_3_3
2 992 Fake Address 3 nan_2
3 992 SC_M_G_1_1
4 992 SC_M_O_1_1
在這個 df 上有工作要做,以將行與相同的Entry組合起來。 對於這些,只有第一行有Address 。 我需要連接ShortOrdDesc列和Address 。 我找到了一個非常有用的鏈接:
以此為基礎,我開發了以下功能:
def f(x):
return pd.Series(dict(A = x['Entry'].sum(),
B = x['Address'].sum(),
C = "%s" % '; '.join(x['ShortOrdDesc'])))
哪個應用使用
myobj = ordersToprint.groupby('Entry').apply(f)
這將返回錯誤:
類型錯誤:必須是 str,而不是 int
查看我的數據,我沒有看到問題是什么,因為我相信對 'Entry' 的整數運行.sum()應該可以工作。
我的代碼或我的方法有什么錯誤?
我認為某些列是數字並且需要string
。
所以使用astype
,如果需要刪除NaN
s 添加dropna
:
def f(x):
return pd.Series(dict(A = x['Entry'].sum(),
B = ''.join(x['Address'].dropna().astype(str)),
C = '; '.join(x['ShortOrdDesc'].astype(str))))
myobj = ordersToprint.groupby('Entry').apply(f)
print (myobj)
A B C
Entry
988 988 Fake Address 1 SC_M_W_3_1
989 989 Fake Address 2 SC_M_W_3_3
992 2976 Fake Address 3 nan_2; SC_M_G_1_1; SC_M_O_1_1
agg
另一個解決方案,但有必要重命名列:
f = {'Entry':'sum',
'Address' : lambda x: ''.join(x.dropna().astype(str)),
'ShortOrdDesc' : lambda x: '; '.join(x.astype(str))}
cols = {'Entry':'A','Address':'B','ShortOrdDesc':'C'}
myobj = ordersToprint.groupby('Entry').agg(f).rename(columns=cols)[['A','B','C']]
print (myobj)
A B C
Entry
988 988 Fake Address 1 SC_M_W_3_1
989 989 Fake Address 2 SC_M_W_3_3
992 2976 Fake Address 3 nan_2; SC_M_G_1_1; SC_M_O_1_1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.