简体   繁体   English

CSV 数据到 Python 字典

[英]CSV data to Python dictionary

I wrote my data which was in lists and dicts to a csv file, and when i import the csv file using pd.read_csv('file.csv') , everything becomes strings.我将列表和字典中的数据写入 csv 文件,当我使用pd.read_csv('file.csv')导入 csv 文件时,一切都变成了字符串。 How can i keep or convert it to its original format?我怎样才能保留或将其转换为原始格式?

Originally, everything was in a dataframe and then written to a CSV file using df.to_csv(r'./file.csv') .最初,所有内容都在 dataframe 中,然后使用df.to_csv(r'./file.csv')写入 CSV 文件。

csv_data['ln2']
Out[36]: 
0        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
1        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
2        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
3        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
4        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
                               ...                        
43244    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43245    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43246    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43247    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43248    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
Name: ln2, Length: 43249, dtype: object

all the rows are strings.所有的行都是字符串。

This will read the column as dicts:这会将列读取为 dicts:

df = pd.read_csv('file.csv', converters={'ln2': eval})

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

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