需要在每次迭代中循环 pandas df 两个连续列名的集合,以在不同的 excel 工作表中创建单独的数据透视表

Need to loop over pandas df set of two consecutive column names in each iteration to create separate pivots in different excel sheets

输入方向:

df = pd.DataFrame({
    'DATE':['200701','200702','200703','200704'],
    'A':['35','42','43','25'],'B':['33','40','39','28'],
    'DIFFERENCE OF A&B':['2','2','4','-3'],
    'C':['26','28','24','19'],'D':['20','25','30','25'],
    'DIFFERENCE OF C&D':['6','3','-6','-6']
})

预期输出:

迭代 1 枢轴:

pivot1 = pd.pivot_table(df,index=['DATE'],values=['A','B','DIFFERENCE OF A&B'],aggfunc='sum')

迭代 2 枢轴:

pivot2 = pd.pivot_table(df,index=['DATE'],values=['C','D','DIFFERENCE OF C&D'],aggfunc='sum')

依此类推接下来的 2 个连续列的数据透视值。

请帮助我,我很挣扎。

pivot_table() 函数似乎对您提供的数据框示例没有任何作用,但是,也许这会起作用。查看内联评论。

df = pd.DataFrame({
    'DATE':['200701','200702','200703','200704'],
    'A':['35','42','43','25'],'B':['33','40','39','28'],
    'DIFFERENCE OF A&B':['2','2','4','-3'],
    'C':['26','28','24','19'],'D':['20','25','30','25'],
    'DIFFERENCE OF C&D':['6','3','-6','-6']
})

df.set_index('DATE', inplace=True) # set the index to DATE

for i in range(0, len(df.columns), 3): # assumes your columns are multiple of 3
    print(df.iloc[: , i:i+3 ]) # find the dataset for successive three columns
    # the next line gives the same output as previous line
    # print(pd.pivot_table(df.iloc[: , i:i+3 ],index=df.iloc[: , i:i+3 ].index,values=df.iloc[: , i:i+3 ].columns.to_list(),aggfunc='sum'))