3 回答
TA贡献1786条经验 获得超11个赞
尝试concat:
dfs = [df,df2, df3]
pd.concat([df.stack() for df in dfs], axis=1)
输出:
0 1 2
age sum 140.00 14.00 528.00
mean 35.00 345.00 700.00
count 4.00 2.00 3.00
offspring sum 45.00 46.00 15.00
mean 11.25 121.25 552.25
count 4.00 2.00 3.00
total_pop sum 17907.00 14607.00 1407.00
mean 4476.75 5476.75 4156.75
count 4.00 2.00 3.00
TA贡献1840条经验 获得超5个赞
如果您不需要循环,这将起作用:
# stack dataframes
df = pd.DataFrame(df.stack(), columns=[1])
df2 = pd.DataFrame(df2.stack(), columns=[2])
df3 = pd.DataFrame(df3.stack(), columns=[3])
#join on index
final_df = df.join(df2).join(df3)
如果您需要使用循环,您可以这样做:
# stack first df
final_df = pd.DataFrame(df.stack(), columns=[1])
# loop through other dfs
for n, next_df in {2: df2, 3: df3}.items():
next_df = pd.DataFrame(next_df.stack(), columns=[n])
final_df = final_df.join(next_df)
TA贡献1859条经验 获得超6个赞
您可以使用pd.concatwith 选项在决赛上keys做一个,而不是每个stackdfstackdf
df_list = [df, df2, df3]
pd.concat(df_list, keys=range(len(df_list)), axis=1).stack()
Out[127]:
0 1 2
age sum 140.00 14.00 528.00
mean 35.00 345.00 700.00
count 4.00 2.00 3.00
offspring sum 45.00 46.00 15.00
mean 11.25 121.25 552.25
count 4.00 2.00 3.00
total_pop sum 17907.00 14607.00 1407.00
mean 4476.75 5476.75 4156.75
count 4.00 2.00 3.00
添加回答
举报