python - Pandas :每 N 列的总和

标签 python pandas

我有数据框

ID   2016-01   2016-02 ...  2017-01  2017-02 ... 2017-10  2017-11  2017-12
111    12        34           0        12          3        0        0
222    0         32           5         5          0        0        0

我需要每 12 列进行计数并得到

ID   2016   2017
111   46     15
222   32     10

我尝试使用

(df.groupby((np.arange(len(df.columns)) // 31) + 1, axis=1).sum().add_prefix('s'))

但它返回到所有列 但是当我尝试使用

df.groupby['ID']((np.arange(len(df.columns)) // 31) + 1, axis=1).sum().add_prefix('s'))

返回

TypeError: 'method' object is not subscriptable

我该如何解决?

最佳答案

第一个set_index所有没有日期的列:

df = df.set_index('ID')

1. groupby split编辑列并首先选择:

df = df.groupby(df.columns.str.split('-').str[0], axis=1).sum()

2. lambda 拆分函数:

df = df.groupby(lambda x: x.split('-')[0], axis=1).sum()

3. 将列转换为日期时间和groupby 年:

df.columns = pd.to_datetime(df.columns)
df = df.groupby(df.columns.year, axis=1).sum()

4. 重采样:

df.columns = pd.to_datetime(df.columns)
df = df.resample('A', axis=1).sum()
df.columns = df.columns.year

print (df)
     2016  2017
ID             
111    46    15
222    32    10

关于python - Pandas :每 N 列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607027/

相关文章:

python - 从python在windows上找到bash可执行文件的位置

python - 在绘图中使用 slider 时如何更改轴标题

python - 大型 XML 文件 - 附加到 Pandas DF - 越来越慢

python - 将相机捕获的视频流式传输到另一个位置

python - 将数据帧更改为索引值对

python - 替换Excel表格中的数据

python - 为什么重写 __getattribute__ 来代理值会搞砸 isinstance?

python - 使用计数将条件排除应用于 Pandas DataFrame

csv - 如何从 CSV 文件读取 pandas 系列

python - 将文本格式的固定宽度表格转换为dataframe/excel/csv