在python中列表是一个非常有用的容器,除了平常用来装数字、字符,我还经常用来装dataframe,或者列表可以作为dataframe的具体值存入,很是舒服。
但问题是,当我们将复杂的数据保存起来的时候,比如常存入Excel,再次导出时,你的数据全部是字符串(str)类型了,这是因为这种保存方式是以文本写入,而不是二进制数据保存,所以你只要存进去,再次导出来就是字符串了。明白了原理,解决方法就很简单了!
# 设置测试数据
Database = pd.DataFrame()
Database['test'] = [['1', '3', '4'], ['2', '3', '5'], ['1', '2', '3', '5'], ['2', '5']]
print('原数据格式类型之列表:', type(Database['test'].iloc[0]))
# 原数据格式类型之列表: <class 'list'>
# 写入excel
Database.to_excel('./Database_str.xlsx', index=False)
# 再读取出来,问题就出现了,list变成了str
Database = pd.read_excel('./Database_str.xlsx')
print('读入后数据格式类型之列表:', type(Database['test'].iloc[0]))
# 读入后数据格式类型之列表: <class 'str'>
解决方法:
1.还原函数(最有效的,简直yyds!)
# 主要函数是eval(),自带的,直接调用即可,也可以写成我这样的map形式
def fun_str_list(x):
x = eval(x) # 格式还原为列表
return x
symptoms = list(map(fun_str_list, Database['test']))
print('还原后数据格式类型之列表:', type(symptoms))
# 还原后数据格式类型之列表: <class 'list'>
2.别存入Excel,其他方式存入,但可能造成不方便,其他Excel软件打不开。
# 用pickle形式存储二进制文件即可
import pickle
1)
# 存储:
Database.to_pickle('./Database.pickle')
# 读取:
Database = pd.read_pickle('./Database.pickle')
2)
# Write to the file
f = open('Database.data', 'wb')
pickle.dump(Database, f) # dump the object to a file
f.close()
# Read back from the file
f = open('Database.data', 'rb')
Database = pickle.load(f) # load the object from file