我试图将pandas数据框保存为excel文件,然后再次导入并将其转换回字典。数据帧很大。例如,请考虑以下代码:
import pandas as pd
path = 'file.xlsx'
dict1 = {'a' : [3, [1, 2, 3], 'text1'],
'b' : [4, [4, 5, 6, 7], 'text2']}
print('\n\nType 1:', type(dict1['a'][1]))
df1 = pd.DataFrame(dict1)
df1.to_excel(path, sheet_name='Sheet1')
print("\n\nSaved df:\n", df1 , '\n\n')
df2 = pd.read_excel(path, sheet_name='Sheet1')
print("\n\nLoaded df:\n", df2 , '\n\n')
dict2 = df2.to_dict(orient='list')
print("New dict:", dict2, '\n\n')
print('Type 2:', type(dict2['a'][1]))
输出为:
Type 1: <class 'list'>
Saved df:
a b
0 3 4
1 [1, 2, 3] [4, 5, 6, 7]
2 text1 text2
Loaded df:
a b
0 3 4
1 [1, 2, 3] [4, 5, 6, 7]
2 text1 text2
New dict: {'a': [3, '[1, 2, 3]', 'text1'], 'b': [4, '[4, 5, 6, 7]', 'text2']}
Type 2: <class 'str'>
你能帮我找回相同元素类型的原始词典吗?
谢谢您!