我有一個這樣的資料:
d1 = pd.DataFrame({"Mother_id"/span>: 11111, "Children_id": [12476, 19684]})
d2 = pd.DataFrame({"Mother_id"/span>: 22222, "Children_id": [24153, 29654, 25417]})
d3 = pd.concat([d1, d2], axis=0)
期望的輸出:
Mother_id child_id_1 child_2 child_3 .... number_of_children
(11111, 12476, 19684, nan, 2)
(22222, 24153, 29654, 25417, 3)
誰能幫幫忙? 謝謝。
uj5u.com熱心網友回復:
這里是一個使用pivot的解決方案。它首先使用groupby cumcount來計算一個帶有子女等級的輔助列,該列將被用來定義透視的列。
(d3.assign(n=d3.groupby('Mother_id') .cumcount().add(1)
.pivot(index='Mother_id'/span>, columns='n', values='Children_id'/span>)
.add_prefix('child_')
.assign(n_children=lambda d: d.notna().sum( axis=1)
)
輸出:
child_1 child_2 child_3 n_children
母親_id
11111 12476.0 19684.0 NaN 2
22222 24153.0 29654.0 25417.0 3
uj5u.com熱心網友回復:
你不僅需要concat,你還需要groupby與行explode
s = pd.concat([d1,d2]).groupby('Mother_id') 。 Children_id.agg(list).apply(pd.Series).add_prefix('child_id_')
s['number_of_child'] = s.notna().sum(1)
s = s.reset_index()
s
Out[95]。
Mother_id child_id_0 child_id_1 child_id_2 number_of_child
0 11111 12476.0 19684.0 NaN 2
1 22222 24153. 0 29654.0 25417.0 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/309185.html
標籤:
上一篇:R:是否可以將knitr::kable轉換為資料幀?
下一篇:如何根據條件洗掉行?
