我想将大型数据帧转换为一系列报告表,这些报告表为数据帧分隔/跳过的 Excel 行中的每个唯一 ID 复制模板。 我想通过一系列循环来做到这一点。 我认为我可以通过将 df 中的每个项目映射到 Excel 文件来完成...但是根据数据帧的大小,这将需要几千行 - 任何帮助将不胜感激!!
import pandas as pd
data = {'id' = [1,2,3]
, 'make' = ['ford','chevrolet','dodge']
, 'model' = ['mustang','comaro','challenger']
, 'year' = ['1969','1970','1971']
, 'color' = ['blue', 'red', 'green']
, 'miles' = ['15000','20000','35000']
, 'seats' = ['leather', 'cloth' , 'leather']
}
df = pd.DataFrame(data)
df.to_excel(r'/desktop/reports/output1.xlsx')
Excel 中的建议结果(id 分组之间跳过一行):
A B C D E F
1 make ford year 1969 miles 15000
2 model mustang color blue seats leather
3
4 make chevrolet year 1970 miles 20000
5 model comaro color red seats cloth
6
7 make dodge year 1971 miles 35000
8 model challenger color green seats leather
代码
# melt & sort
tmp = df.melt('id', var_name='a', value_name='b').sort_values('id', kind='stable')
# make id's cumcount to variable s
s = tmp.groupby('id').cumcount()
# assign 'row' and 'col' based on the cumulative count
tmp['row'], tmp['col'] = s % 2, s // 2
# pivot
tmp = (tmp.pivot(index=['id', 'row'], columns='col')
.swaplevel(0, 1, axis=1).sort_index(axis=1).droplevel(0, axis=1)
)
# create idx(MultiIndex) for making blank rows
idx = pd.MultiIndex.from_product([df['id'].unique(), [0, 1, 2]])
# reindex with idx & save to Excel file without index and header
tmp.reindex(idx).to_excel('no1.xlsx', index=False, header=False)
结果: