如何将一列拆分为多个列?



我有一个这样的数据:

d1 = pd.DataFrame({"Mother_id": 11111, "Children_id": [12476, 19684]})
d2 = pd.DataFrame({"Mother_id": 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)

下面是使用pivot的解决方案。它首先使用groupby+cumcount计算一个辅助列,其中包含子列的秩,该子列将用于定义pivot的列。

(d3.assign(n=d3.groupby('Mother_id').cumcount().add(1))
.pivot(index='Mother_id', columns='n', values='Children_id')
.add_prefix('child_')
.assign(n_children=lambda d: d.notna().sum(axis=1))
)

输出:

child_1  child_2  child_3  n_children
Mother_id                                       
11111      12476.0  19684.0      NaN           2
22222      24153.0  29654.0  25417.0           3

最新更新