I'm trying to save a pandas DataFrame as an excel file and import it again and convert it back to a dictionary. The data frame is quite large in size. For instance, consider the following code:
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]))
The output is:
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'>
Could you help me get back the original dictionary with the same element types? Thank you!