将多个数据帧附加到不同工作表上的 excel
Appending multiple dataframes to excel on different sheets
我想将字典中的多个数据帧添加到一个 excel 文件中,每个数据帧都应该写在 sheet 中。 Sheen 名字实际上是字典的关键字。以下代码
for key in df_dict:
df = df_dict[key]
df.to_excel('data-frames.xlsx', sheet_name=key, index=False)
只写最后一个数据帧。所以,我只看到一个sheet。另一方面,描述为 的 append_df_to_excel()
方法不起作用。我得到的错误是没有这样的方法,尽管 pandas 版本是 1.4.2.
...
AttributeError: 'DataFrame' object has no attribute 'append_df_to_excel'
In [2]: import pandas as pd
In [2]: print(pd.__version__)
1.4.2
我该如何解决?
你能试试这个代码吗?
for key in df_dict:
df = df_dict[key].copy()
with pd.ExcelWriter('data-frames.xlsx', mode='a') as writer:
df.to_excel(writer, sheet_name=key)
这是一种完成您所要求的方法:
import pandas as pd
df_dict = {f'key_{i}':pd.DataFrame([[i+1,i+2,i+3],['a','b','c']], columns=['first','second','third']) for i in range(4)}
[print(f'{k}:\n{df}') for k, df in df_dict.items()]
with pd.ExcelWriter('TestOutput.xlsx') as writer:
for sheet, df in df_dict.items():
df.to_excel(writer, index=None, sheet_name=sheet)
输入
key_0:
first second third
0 1 2 3
1 a b c
key_1:
first second third
0 2 3 4
1 a b c
key_2:
first second third
0 3 4 5
1 a b c
key_3:
first second third
0 4 5 6
1 a b c
输出
Excel file TestOutput.xlsx
with four sheets named key_1
, key_1
, key_3
, and key_4
, each containing 3 columns named first
, second
, and third
with two rows of data.
我想将字典中的多个数据帧添加到一个 excel 文件中,每个数据帧都应该写在 sheet 中。 Sheen 名字实际上是字典的关键字。以下代码
for key in df_dict:
df = df_dict[key]
df.to_excel('data-frames.xlsx', sheet_name=key, index=False)
只写最后一个数据帧。所以,我只看到一个sheet。另一方面,描述为 append_df_to_excel()
方法不起作用。我得到的错误是没有这样的方法,尽管 pandas 版本是 1.4.2.
...
AttributeError: 'DataFrame' object has no attribute 'append_df_to_excel'
In [2]: import pandas as pd
In [2]: print(pd.__version__)
1.4.2
我该如何解决?
你能试试这个代码吗?
for key in df_dict:
df = df_dict[key].copy()
with pd.ExcelWriter('data-frames.xlsx', mode='a') as writer:
df.to_excel(writer, sheet_name=key)
这是一种完成您所要求的方法:
import pandas as pd
df_dict = {f'key_{i}':pd.DataFrame([[i+1,i+2,i+3],['a','b','c']], columns=['first','second','third']) for i in range(4)}
[print(f'{k}:\n{df}') for k, df in df_dict.items()]
with pd.ExcelWriter('TestOutput.xlsx') as writer:
for sheet, df in df_dict.items():
df.to_excel(writer, index=None, sheet_name=sheet)
输入
key_0:
first second third
0 1 2 3
1 a b c
key_1:
first second third
0 2 3 4
1 a b c
key_2:
first second third
0 3 4 5
1 a b c
key_3:
first second third
0 4 5 6
1 a b c
输出
Excel file
TestOutput.xlsx
with four sheets namedkey_1
,key_1
,key_3
, andkey_4
, each containing 3 columns namedfirst
,second
, andthird
with two rows of data.