【问题标题】:Multiple List in One Full List (Not list in a list) [duplicate]一个完整列表中的多个列表(不在列表中列出)[重复]
【发布时间】:2021-03-15 04:36:32
【问题描述】:

我在数据框中的每一行都有一个列表,我想将它合并到一个完整的列表中。

data = {'row 1': ["text 1", "text 2", "text 3"],
        'row 2': ["text 4", "text 5", "text 6"],'row 3':["text 7", "text 8", "text 9"]
        }
dataframe = pd.DataFrame (data, columns = ['row 1','row 2','row 3'])
dataframe

expected output: ["text 1", "text 2", "text 3", "text 4", "text 5", "text 6", "text 7", "text 8", "text 9"]

我已经尝试过 df.iterrows 但它最终成为多个列表的列表...

total =[]
for index, row in df.iterrows():
   total.extend(row)

output: [["text 1", "text 2", "text 3"],["text 4", "text 5", "text 6"],["text 7", "text 8", "text 9"]]

【问题讨论】:

  • 请将示例 DF 显示为代码而不是图像。
  • 可以试试 row[:] 吗?
  • 你可以flatten the list
  • 另外,您的代码有缩进错误
  • 已编辑 :) 对此感到抱歉。

标签: python list


【解决方案1】:

使用.explode():

df.explode('col2').values.tolist()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2020-05-02
    • 2022-12-24
    相关资源
    最近更新 更多