简体   繁体   English

如何从 csv 文件中加载 pandas 列,其中列表作为列表而不是字符串

[英]How to load a pandas column from a csv file with lists as lists and not as strings

when I write a list in pandas when I read it, its dtype is string and not array, is there any way to write a column of list in such a way that be again array type when we read it?当我在 pandas 中写入列表时,当我读取它时,它的 dtype 是字符串而不是数组,有没有办法以这样的方式写入列表列,当我们读取它时又是数组类型?

Here is what I mean:这就是我的意思:

d=[['d',['A','B','C']],['p',['F','G']]]

df=pd.DataFrame(d)

df.to_csv('file.csv')

when I run the following code,当我运行以下代码时,

pd.read_csv('file.csv')['1'].values[0] 

the output is: output 是:

 "['A', 'B', 'C']"

but I want this:但我想要这个:

  ['A', 'B', 'C']

one solution would be to run it through literal_eval .一种解决方案是通过literal_eval运行它。

you make a dictionary with the column name as key and the converter function as value.你创建一个字典,列名作为键,转换器 function 作为值。 and pass that into read_csv with the keyword converters并使用关键字转换器将其传递给 read_csv

Note that if your column has mixed data (also strings and other stuff) you might want to write a custom function which filters and converts the different types请注意,如果您的列包含混合数据(还有字符串和其他内容),您可能需要编写自定义 function 来过滤和转换不同类型

from ast import literal_eval
df1 = pd.read_csv('file.csv', converters={'1': literal_eval})
df1

output: output: 在此处输入图像描述

type(df1["1"][0])

output: output:

在此处输入图像描述

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

相关问题 在pandas中如何读取列中列表的csv文件? - In pandas how to read csv files with lists in a column? 将列表写入pandas dataframe到csv,从csv读取dataframe并再次转换为列表而没有字符串 - write lists to pandas dataframe to csv, read dataframe from csv and convert to lists again without having strings 从 csv 文件读取/写入字符串、整数和字符串列表的字典 - read/write dictionary of strings, integers, and lists of strings from/to csv file 在带有字符串和列表列的熊猫列上运行函数 - Run a function on a pandas column with strings and column of lists 列作为一系列字符串列表导出到CSV,在已读取的Pandas上解释为仅一系列字符串 - Column exported to CSV as series of lists of strings, on read Pandas interprets as just series of strings 如何在列表的 Pandas 列中获取唯一列表 - How to get unique lists in a Pandas column of lists 如何从pandas中的列创建唯一ID列表,其中ID列表在Python中被提及为字符串 - How to create a list of unique ID from a column in pandas where lists of ID are mentioned as strings in Python 如何从多个列表中制作CSV文件? - How to make a CSV file from a number of lists? 将 int 分配给 Pandas 中一列列表中的字符串 - Assign int to strings in a column of lists in pandas 将字符串转换为 pandas dataframe 列中的项目列表 - Turning strings into lists of items in a pandas dataframe column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM