如何将列中的列表保存为CSV?



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

数据框中的列

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

在excel中如何显示

但是我想让它看起来像这样

在excel中应该是什么样子

我怎么才能做到呢?谢谢。

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

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

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

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

最新更新