简体   繁体   English

保存和加载列表值?

[英]saving and loading list values?

I have a dataframe where one of the columns contains a list of values:我有一个 dataframe,其中一列包含值列表:

example: type(df['col_list'].values[0]) = list示例: type(df['col_list'].values[0]) = list

I saved this dataframe as csv file ( df.to_csv('my_file.csv') )我将这个 dataframe 保存为 csv 文件 ( df.to_csv('my_file.csv') )

When I load the dataframe ( df = pd.read_csv('my_file.csv') ) the column which contains list of values change to string type: type(df['col_list'].values[0]) = str当我加载 dataframe ( df = pd.read_csv('my_file.csv') ) 包含值列表的列更改为string类型: type(df['col_list'].values[0]) = str

When converting to list ( list(df['col_list'].values[0] ) I'm getting list of characters instead of list of values.转换为列表时( list(df['col_list'].values[0] )我得到的是字符列表而不是值列表。

How can I save/load dataframe which one of it's columns contains list of values?如何保存/加载 dataframe 其中一列包含值列表?

Use JSON or HDF file format instead of CSV. CSV file format is really inconvenient for storing a list or a collection of objects.使用JSONHDF文件格式,而不是 CSV。CSV 文件格式对于存储列表或对象集合确实很不方便。

This is due to the table being saved as CSV and serializing the values of the list.这是因为表被保存为 CSV 并序列化了列表的值。 The csv format is unable to save the list object as it is. csv格式无法原样保存列表object。 Try saving in another format df.to_pickle('test.df') .尝试以另一种格式保存df.to_pickle('test.df') You can then read this back into a dataframe with read_pickle然后,您可以使用 read_pickle 将其读回dataframe

Read more on saving to pickle here这里阅读更多关于保存到泡菜的信息

I think Anurag's suggestion is very good.我认为 Anurag 的建议非常好。 But just in case you want to keep things the way it is, this will do the job但以防万一你想保持原样,这就可以了

import json
df['col_list'] = df['col_list'].apply(json.loads)

This would work better if you had converted col_list into JSON text before pd.to_csv by如果您在 pd.to_csv 之前将col_list转换为 JSON 文本, pd.to_csv会更好

df['col_list'] = df['col_list'].apply(json.dumps)

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

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