简体   繁体   English

Dataframe 包含到 CSV 的嵌套列表

[英]Dataframe containing nested lists to CSV

I have a dataframe which has nested lists as column values like given below:我有一个 dataframe,它有嵌套列表作为列值,如下所示:

    col1         col2   
0   [1, 1]      [a, b, c]   
1   [0, 0, 0]   [d, e, f]   

When I convert the dataframe to csv, I get something like this:当我将 dataframe 转换为 csv 时,我得到如下信息:

   col1      col2   
  [1 1]  ,  [a b c] 
  [0 0 0] , [d e f] 

Basically, the commas from the nested lists disappear and when I read back the dataframe from csv I don't get the commas.基本上,嵌套列表中的逗号消失了,当我从 csv 读回 dataframe 时,我没有得到逗号。 How can I maintain the commas and save the csv to something like this:如何维护逗号并将 csv 保存为如下所示:

   col1          col2   
  [1,1]    ,    [a, b, c]   
  [0, 0, 0] ,   [d, e, f]   

PS: I would like a pandas solution to creating the csv PS:我想要一个 pandas 解决方案来创建 csv

I think there are not lists, but arrays, so if write to csv comma are removed:我认为没有列表,但是 arrays,所以如果写入 csv 逗号被删除:

df = pd.DataFrame({'col1':[np.array([1,1]), np.array([0,0,0])]})
print (df)
        col1
0     [1, 1]
1  [0, 0, 0]

df.to_csv('file.csv', index=False)

df = pd.read_csv('file.csv')
print (df)
      col1
0    [1 1]
1  [0 0 0]

Possible solution is convert arrays to lists:可能的解决方案是将 arrays 转换为列表:

df = pd.DataFrame({'col1':[np.array([1,1]), np.array([0,0,0])]})

df = df.applymap(list)
print (df)
        col1
0     [1, 1]
1  [0, 0, 0]

df.to_csv('file.csv', index=False)

df = pd.read_csv('file.csv')
print (df)
        col1
0     [1, 1]
1  [0, 0, 0]

Last for lists from string representation of lists use:最后对于列表的字符串表示形式的列表使用:

import ast

df = df.applymap(ast.literal_eval)
print (df)
        col1
0     [1, 1]
1  [0, 0, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM