简体   繁体   English

如何将一列拆分为多列?

[英]How can i split a column into multiple columns?

I have a data like this:我有这样的数据:

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)

Desired Output:期望的输出:

    Mother_id   child_id_1  child_2 child_3 ....  number_of_children
(11111, 12476, 19684, nan, 2)
(22222, 24153, 29654, 25417, 3)

Here is a solution using pivot .这是使用pivot的解决方案。 It first uses groupby + cumcount to compute a helper column with the children's rank that will be used to define the columns for the pivot.它首先使用groupby + cumcount来计算一个具有子级排名的辅助列,该列将用于定义枢轴的列。

(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))
)

output:输出:

           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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM