“取消堆叠"包含多行列表的pandas列 [英] "unstack" a pandas column containing lists into multiple rows

查看:66
本文介绍了“取消堆叠"包含多行列表的pandas列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下熊猫数据框:

Say I have the following Pandas Dataframe:

df = pd.DataFrame({"a" : [1,2,3], "b" : [[1,2],[2,3,4],[5]]})
   a          b
0  1     [1, 2]
1  2  [2, 3, 4]
2  3        [5]

我如何堆叠""b"列中的列表以将其转换为数据框:

How would I "unstack" the lists in the "b" column in order to transform it into the dataframe:

   a  b
0  1  1
1  1  2
2  2  2
3  2  3
4  2  4
5  3  5

推荐答案

更新:通用矢量化方法-也适用于多列DF:

UPDATE: generic vectorized approach - will work also for multiple columns DFs:

假设我们有以下DF:

In [159]: df
Out[159]:
   a          b  c
0  1     [1, 2]  5
1  2  [2, 3, 4]  6
2  3        [5]  7

解决方案:

In [160]: lst_col = 'b'

In [161]: pd.DataFrame({
     ...:     col:np.repeat(df[col].values, df[lst_col].str.len())
     ...:     for col in df.columns.difference([lst_col])
     ...: }).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns.tolist()]
     ...:
Out[161]:
   a  b  c
0  1  1  5
1  1  2  5
2  2  2  6
3  2  3  6
4  2  4  6
5  3  5  7

设置:

df = pd.DataFrame({
    "a" : [1,2,3],
    "b" : [[1,2],[2,3,4],[5]],
    "c" : [5,6,7]
})

矢量化NumPy方法:

Vectorized NumPy approach:

In [124]: pd.DataFrame({'a':np.repeat(df.a.values, df.b.str.len()),
                        'b':np.concatenate(df.b.values)})
Out[124]:
   a  b
0  1  1
1  1  2
2  2  2
3  2  3
4  2  4
5  3  5

老答案:

尝试一下:

In [89]: df.set_index('a', append=True).b.apply(pd.Series).stack().reset_index(level=[0, 2], drop=True).reset_index()
Out[89]:
   a    0
0  1  1.0
1  1  2.0
2  2  2.0
3  2  3.0
4  2  4.0
5  3  5.0

更好的解决方案由@Boud提供:

In [110]: df.set_index('a').b.apply(pd.Series).stack().reset_index(level=-1, drop=True).astype(int).reset_index()
Out[110]:
   a  0
0  1  1
1  1  2
2  2  2
3  2  3
4  2  4
5  3  5

这篇关于“取消堆叠"包含多行列表的pandas列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆