gpt4 book ai didi

python - 基于模式和应用函数的更 pandorean 方式来合并列

转载 作者:行者123 更新时间:2023-11-28 22:30:40 24 4
gpt4 key购买 nike

我想知道是否有更好的方法来根据重复模式对列进行分组,然后应用函数。简单版本是我有按月计算的数据,但想要按季度计算。为了到达那里,我需要每 3 个月进行一次并应用 mean()

    RegionName  State   1997-01 1997-02 1997-03 1997-04 1997-05 1997-06
1 Los Angeles CA 83 19 40 47 76 48
2 Chicago IL 39 87 48 3 71 18
3 Philadelphia PA 60 85 8 46 81 48

期望的结果是:

    RegionName  State   1997q1      1997q2
1 Los Angeles CA 47.33333333 57
2 Chicago IL 58 30.66666667
3 Philadelphia PA 51 58.33333333

我有一个非常 hacky 的方式来使用 python 循环和预制的数字阶梯列表:

quartersbyendingdigit = {'1':'q1', '4':'q2', '7':'q3', '0':'q4'}
rl = list(range(2, housingdf.shape[1], 3))
for each in rl:
og_column = housingdf.columns[each]
new_column = og_column[:4] + quartersbyendingdigit[ og_column[-1] ]
housingdf[new_column] = (housingdf[housingdf.columns[each]] + housingdf[housingdf.columns[each+1]] + housingdf[housingdf.columns[each+2]])/3

我不得不想象 Pandas 有更好的方法来做到这一点,因为它的模式非常明显。

最佳答案

您可以将日期时间列转换为季度周期,然后使用 axis = 1 按列对数据帧进行分组;

df.set_index(["RegionName", "State"], inplace=True)    
df.columns = pd.to_datetime(df.columns).to_period("Q")
df.groupby(level = 0, axis = 1).mean().reset_index()

enter image description here

关于python - 基于模式和应用函数的更 pandorean 方式来合并列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048447/

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