gpt4 book ai didi

python - 将多列转换为一行 (Pandas/Numpy)

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:50 31 4
gpt4 key购买 nike

我想将多个属性的月度数据合并到包含全年数据的一行中。这与 Combine multiple time-series rows into one row with Pandas 类似。 .如果我的年份中的月份是完整的,那么这个问题的解决方案对我有用,但对于我的大部分数据月份来说,个别年份都缺失了。如果只有 12 月的数据,解决方案将填充第一列而不是第 12 列。

例如,我只使用一月到六月。

这是我的数据示例:

ex_df = pd.DataFrame({'year': [1966, 1966, 1966, 1967, 1967, 1967], 'month': [1, 2, 6, 2, 3, 4], 'A': [10, 5, 0, np.nan, 25, 0], 'B': [-100, -80, 100, -120, 0, 60], 'C': [-1, -18, -2, -11, 10, 6]})

这是最优解:

sol_df = pd.DataFrame({'year': [1966, 1967], 'A1': [10, np.nan], 'A2': [5, np.nan],'A3': [np.nan, 25],'A4': [np.nan, 0],'A5': [np.nan, np.nan],'A6': [0, np.nan],'B1': [-100, np.nan],  'B2': [-80, -120], 'B3': [np.nan, 0], 'B4': [np.nan, 60], 'B5': [np.nan, np.nan], 'B6': [100, np.nan],'C1': [-1, np.nan],  'C2': [-18, -11], 'C3': [np.nan, 10], 'C4': [np.nan, 6], 'C5': [np.nan, np.nan], 'C6': [-2, np.nan] })

A、B、C为属性,数字对应月份。

最佳答案

使用:

df = ex_df.set_index(['year','month']).unstack()
df.columns = ['{}{}'.format(x, y) for x, y in df.columns]
df = df.reset_index()
print (df)
year A1 A2 A3 A4 A6 B1 B2 B3 B4 B6 C1 C2 \
0 1966 10.0 5.0 NaN NaN 0.0 -100.0 -80.0 NaN NaN 100.0 -1.0 -18.0
1 1967 NaN NaN 25.0 0.0 NaN NaN -120.0 0.0 60.0 NaN NaN -11.0

C3 C4 C6
0 NaN NaN -2.0

解释:

  1. 第一个set_indexunstack reshape
  2. 在具有列表理解的列中展平 Multiindex
  3. 根据 reset_index 的索引创建列

关于python - 将多列转换为一行 (Pandas/Numpy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50676331/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com