我有一个 df,其中国家作为索引,年份 (1990-2015) 作为标题。我想制作一个新的 df2,其中每一列都是 5 年的总和,例如:1995-1999、2000-2004 等 我这样做了:
df2 = pd.DataFrame(index=df.index[:], columns=['1995', '2000', '2005', '2010', '2015'])
df2['1995'] = df.iloc[0:4].sum(axis=1)
但它不会取代 NaN 值。 我究竟做错了什么?提前致谢
最佳答案
第一步
使用 df.T.reset_index
转置和重置索引
df2 = df.T.reset_index(drop=True)
第 2 步
使用 df.groupby
, 以 5 为一组按索引分组,然后与 dfGroupBy.agg
求和, 通过 np.nansum
df2 = df2.groupby(df2.index // 5).agg(np.nansum).T
第 3 步
就地分配列
df2.columns = pd.to_datetime(df.columns[::5]).year + 5
df = ... # Borrowed from Bharath
df2 = df.T.reset_index(drop=True)
df2 = df2.groupby(df2.index // 5).sum().T
df2.columns = pd.to_datetime(df.columns[::5]).year + 5
print(df2)
输出:
1995 2000 2005 2010
Country
IN 72 29 100 2
EG 31 40 40 24
关于python - 为什么不替换新数据框中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45524655/