[英]Pandas combine columns values into cells of a row by type
我有這個數據幀
ID type name number description comments
1 short A 2 XX xxx
1 short B
1 short C 4 YY yyy
1 full A/B/C
2 short E
2 short F 9 ZZ zzz
2 short G 7 WW www
2 short H
2 full E/F/G/H
我想在倒塌把它改造成type full
行number
, description
和comments
在列中的值(如果它們存在) type short
行
id type name number description comments
1 full A/B/C 2/4 XX/YY xxx/yyy
2 full E/F/G/H 9/7 ZZ/WW zzz/www
我嘗試使用聚合和groupby函數,但沒有成功。
你可以幫幫我嗎?
提前致謝!
您可以使用帶有lambda函數的dict.fromkeys
為所有列創建動態字典, dict.fromkeys
包含字典d1
id
和鍵,並傳遞給GroupBy.agg
:
f = lambda x: '/'.join(x.dropna().astype(str))
d1 = {'type':'last', 'name':'last'}
d2 = dict.fromkeys(df.columns.difference(['id'] + list(d1.keys())), f)
d = {**d1, **d2}
df = df.groupby('id', sort=False, as_index=False).agg(d)
print (df)
id type name comments description number
0 1 full A/B/C xxx/yyy XX/YY 2.0/4.0
1 2 full E/F/G/H zzz/www ZZ/WW 9.0/7.0
如果需要按類型處理lambda函數中的值 - 例如數字的總和和非數字列的連接:
f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else '/'.join(x.dropna())
d1 = {'type':'last', 'name':'last'}
d2 = dict.fromkeys(df.columns.difference(['id'] + list(d1.keys())), f)
d = {**d1, **d2}
df = df.groupby('id', sort=False, as_index=False).agg(d)
print (df)
id type name comments description number
0 1 full A/B/C xxx/yyy XX/YY 6.0
1 2 full E/F/G/H zzz/www ZZ/WW 16.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.