【问题标题】:Is there any way to split the columns of list to rows in pandas [duplicate]有没有办法将列表的列拆分为熊猫中的行[重复]
【发布时间】:2021-08-13 19:58:28
【问题描述】:

在熊猫中,我想改变数据格式如下。 在我看来,我只知道使用 open('filename') 逐行读取并在 readline 之后解析。 在 python pandas 中有什么方法可以解决这个问题。

来自

Column A Column B
A [1,2,3]
B [4,5,6]

Column A Column B
A 1
A 2
A 3
B 4
B 5
B 6

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用explode:

    df = df.explode('Column B')
    

    另一种方式通过list comprehension

    d = {'Column A': {0: 'A', 1: 'B'}, 'Column B': {0: [1, 2, 3], 1: [4, 5, 6]}}
    df = pd.DataFrame(d)
    
    df = pd.DataFrame([[x] + [z] for x, y in df.values for z in y],columns=df.columns)
    

    【讨论】:

    • 谢谢。这对我的编程很有帮助。
    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2019-11-26
    • 2018-11-16
    • 2018-07-26
    • 1970-01-01
    • 2022-06-25
    相关资源
    最近更新 更多