简体   繁体   English

Python pandas从csv文件中读取列表数据类型中的列表

[英]Python pandas read list in list data type from csv file

I have a csv file, like this: 我有一个csv文件,像这样:

A       B
aaa     [['a1','b1'],['a2','b2']]
bbb     [['a3','b3']]

I tried to read this file into python. 我试着将这个文件读入python。 And I want the 'B' column in list data type. 我想要列表数据类型中的'B'列。
I tried pd.read_csv('filename.csv') , what I got is "[['a1','b1'],['a2','b2']]" in str type, not in list type. 我试过pd.read_csv('filename.csv') ,得到的是"[['a1','b1'],['a2','b2']]"在str类型中,而不是列表类型。
And I also tried pd.read_csv('filename.csv', converters={'B':list}) , what I got here is like: [[, [',a','1,','b,'...., not the list I want. 我也试过pd.read_csv('filename.csv', converters={'B':list}) ,我在这里得到的是:[[,[',a','1,','b,' ....,不是我想要的清单。
Could you tell me how to read the list from a csv file directly? 你能告诉我如何直接从csv文件中读取列表吗? Thank you so much. 非常感谢。

The issue here is caused by the serialization format of the list in column B . 这里的问题是由列B中 list的序列化格式引起的。 It is stored as a string representation of the list. 它存储为列表的字符串表示形式。 In order to recover a python list back from the string, you can use eval as a converter: 为了从字符串中恢复python列表,您可以使用eval作为转换器:

df = pd.read_csv(source, converters={'B': eval})

to read list you should try this 阅读列表你应该试试这个

import csv
with open('filename.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print your_list

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

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