I have a dictionary that contains multiple dataframes that I created using loops. Basically because I want to split the input data file into smaller dataframes with a rule. The main input data file has variables x1, x2, x3, x4, and each smaller data frame has only observations of the main input where x1 = 0, x2 = 0 etc. like this:
data={}
Iteration = [x1, x2, x3, x4]
for n in iteration:
frame = pd.DataFrame(input file)
omit = (frame[n] ==0 )
data[n] = pd.Dataframe(frame.loc[~omit])
And data now is a dict that holds all the smaller data frames. But I want to save each of those data frames into Excel. I reckon that to do that, I have to "break" the dict data into small data frames by using loops. So I tried:
for n in data.items():
locals()['frame_{n}'.format(n)] = pd.DataFrame.from_dict(data[n])
But it doesn't work, because data frames need 2 parameters, but dict has only 1. What can I do?
Assuming dfs
is a dictionary of dataframes, you can write all dataframes to Excel with the dictionary key as the sheet name:
with pd.ExcelWriter(file, engine='xlsxwriter') as writer:
for sheet, df in dfs.items():
df.to_excel(writer, sheet_name=sheet)
To write as separate files:
for key, df in dfs.items():
df.to_excel(f'___path___/{key}.xlsx')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.