如何在熊猫中将字符串平展为几列?

时间:2021-07-05 09:56:07

标签: pandas

fruit = pd.DataFrame({'type': ['apple: 1 orange: 2 pear: 3']})

我想扁平化数据框并获得以下格式:

苹果橙梨
1 2 3

谢谢

1 个答案:

答案 0 :(得分:1)

如果您在一个字段中处理多个值,您的生活就会变得极其困难。您基本上可以不使用任何 Pandas 函数,因为它们都假设字段中的数据属于一起并且应该保持在一起。

例如用

In [10]: fruit = pd.Series({'apple': 1, 'orange': 2, 'pear': 3})

In [11]: fruit
Out[11]: 
apple     1
orange    2
pear      3
dtype: int64

您可以像这样轻松地转换数据

In [14]: fruit.to_frame()
Out[14]: 
        0
apple   1
orange  2
pear    3

In [15]: fruit.to_frame().T
Out[15]: 
   apple  orange  pear
0      1       2     3
相关问题