作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道是否有更好的方法来根据重复模式对列进行分组,然后应用函数。简单版本是我有按月计算的数据,但想要按季度计算。为了到达那里,我需要每 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()
关于python - 基于模式和应用函数的更 pandorean 方式来合并列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048447/
我想知道是否有更好的方法来根据重复模式对列进行分组,然后应用函数。简单版本是我有按月计算的数据,但想要按季度计算。为了到达那里,我需要每 3 个月进行一次并应用 mean() RegionNa
我是一名优秀的程序员,十分优秀!