[英]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
type(df1["1"][0])
output: output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.