【问题标题】:How to save a list in a column to CSV?如何将列中的列表保存到 CSV?
【发布时间】:2021-11-06 17:54:58
【问题描述】:

我在数据框中有一列看起来像这样。

A column in dataframe

当我将数据框保存到 CSV 时,它看起来像这样。

How it looks like in excel

但我希望它看起来像这样

How it should look like in excel

我怎样才能做到这一点?谢谢。

【问题讨论】:

  • 您只需要逗号,还是还需要在 Excel 中的不同行中包含列表的每个元素?

标签: arrays pandas list dataframe csv


【解决方案1】:

您需要将数组转换为列表:

df['col1']=df['col1'].apply(lambda x: list(x))

示例:

>>> df
             col1  col2
0  [test1, test2]  row1
>>> df['col1'][0]
array(['test1', 'test2'], dtype=object)
>>> df.to_csv('a.csv')
$ cat a.csv 
,col1,col2
0,['test1' 'test2'],row1

应用list()后:

>>> df['col1']=df['col1'].apply(lambda x: list(x))
>>> df['col1'][0]
['test1', 'test2']
>>> df.to_csv('a.csv')
$ cat a.csv 
,col1,col2
0,"['test1', 'test2']",row1

【讨论】:

    【解决方案2】:

    保存文件时添加逗号分隔符 https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html

    df.to_csv(filename,sep=',')
    

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 2020-10-09
      • 1970-01-01
      • 2016-08-20
      • 2016-05-17
      • 2016-03-14
      • 1970-01-01
      • 2018-05-05
      • 2021-07-04
      相关资源
      最近更新 更多