Skip to main content
 首页 » 编程设计

python之如何遍历系列以生成数据框并向其添加列

2025年05月04日13落叶无声

我有一堆系列我想堆叠,制作一个数据框,然后通过相同的过程将其他系列添加到该数据框。

我已经在 jupyter notebook 中一步一步地完成了,但是当我尝试在 jupyter notebook 中创建一个 for 语句和一个函数来做我能做的(逐步)时,程序失败并给我一个错误。

代码:

import pandas as pd 
 
data = {'sum':[140.0, 45.0, 17907.0], 'mean':[35.00, 11.25, 4476.75],'count':[4, 4, 4]} 
df = pd.DataFrame(data, index=['age', 'offspring', 'total_pop']) 
data2 = {'sum':[14.0, 46.0, 14607.0], 'mean':[345.00, 121.25, 5476.75], 'count':[2, 2, 2]} 
df2 = pd.DataFrame(data2, index=['age', 'offspring', 'total_pop']) 
data3 = {'sum':[528.0, 15.0, 1407.0], 'mean':[700.00, 552.25, 4156.75], 'count':[3, 3, 3]} 
df3 = pd.DataFrame(data3, index=['age', 'offspring', 'total_pop']) 
 
def dosomething(df): 
        stacked = df.stack() 
        df = pd.Series(stacked) 
        df.to_frame() 
        dfd = pd.DataFrame(df) 
        df = df.join(dfd) 
        print(dfd) 
 
total_df = [(df1), (df2), (df3,)] 
 
for n in range(0, len(total_df)): 
        total_df[n] = dosomething(total_df[n]) 

预期:

                      1         2        3 
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 

实际错误:

ValueError: columns overlap but no suffix specified: RangeIndex(start=0, stop=1, step=1)

请您参考如下方法:

尝试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