Skip to main content
 首页 » 编程设计

python之在 Pandas 中添加多列

2025年05月04日22dflying

刚刚熟悉 pandas,我遇到了 groupby 的问题。

我有一些 CSV 数据,我已将其整理成以下格式:

时间, AAA, BBB, AAA, BBB 20161201 9:00:00, 10, 20, 11, 21 20161201 9:00:01, 10, 20, 11, 21 20161201 9:00:02, 10, 20, 11, 21

我想将其转换为以下内容:

时间,AAA,BBB 20161201 9:00:00, 21, 41 20161201 9:00:01, 21, 41 20161201 9:00:02, 21, 41

我正在使用以下内容:

df.groupby(df.columns, axis=1).sum()

我得到的是:

AAA, BBB, 时间 21, 41, 0.0 21, 41, 0.0 21, 41, 0.0

  1. 如何防止 pandas 对时间列求和?我尝试了以下方法:

    df.groupby([c for c in df.columns if c != "Time"], axis=1).sum()

    但这给出了错误:

    'AAA' 非一维石斑鱼

  2. 如何避免 pandas 移动时间列?

如果重要的话,我将两个 pandas DataFrame 组合在一起以使用以下方法获取上述数据:

df = pd.merge(df1, df2, how="outer") 

然后重命名一些列以缩短名称,以便我可以对它们进行分组。

请您参考如下方法:

df.set_index('Time').groupby(axis=1, level=0).sum().reset_index() 
 
               Time  AAA  BBB 
0  20161201 9:00:00   21   41 
1  20161201 9:00:01   21   41 
2  20161201 9:00:02   21   41