Код: Выделить всё
# Read lookup file which only contains 5 columns.
df_lookup = pd.read_excel(
os.path.join(path, 'lookup.xlsx'),
index_col=[0, 1, 2, 3, 4])
# sample df_lookup
# |A |B |C |D |E |
# |--|--|--|--|--|
# |a1|b1|c1|d1|e1|
# Read data file
df = pd.read_excel(os.path.join(path, 'data.xlsx'))
# Create pivot table from df
# index=['A', 'B', 'C', 'D', 'E'] corresponds to index_col=[0, 1, 2, 3, 4]
df_pivot = pd.pivot_table(
df,
values='count',
index=['A', 'B', 'C', 'D', 'E'],
columns=['Year', 'Month_Num', 'Month'],
aggfunc=np.sum,
margins=True,
margins_name='Total',
fill_value=0)
# sample df_pivot
# |Year |2024 |
# |Month_Num| 12 |
# |Month | Dec |
# |A|B|C|D|E |-----|
# |-|-|-|-|---------|-----|
# |a|b|c|d|e | |
# Merge both tables
df_merge = pd.merge(
df_lookup,
df_pivot,
how='left',
left_index=True,
right_index=True)
# Expected result
# |Year |2024 |
# |Month_Num| 12 |
# |Month | Dec |
# |A |B |C |D |E |-----|
# |--|--|--|--|---------|-----|
# |a1|b1|c1|d1|e1 | |
Подробнее здесь: https://stackoverflow.com/questions/797 ... -dataframe