gpt4 book ai didi

python - 修复 Pandas 中的 Groupby 长度

转载 作者:行者123 更新时间:2023-12-01 01:01:48 24 4
gpt4 key购买 nike

我有一个按 Pandas 数据框分组的:

id    date    temperature
1 2011-9-12 12
2011-9-18 12
2011-9-19 12
2 2011-9-12 15
3 2011-9-12 15
2011-9-16 15

这里,每个id有不同数量的温度记录。

我想修复它们,即每个 id 的平均记录数(比如 3)。如果某些记录丢失,我想首先添加零。

即我的最终数据框应该是:

id    temperature
1 12
12
12
2 0
0
15
3 0
3 15
3 15

我需要将每个 id 的记录数自定义为某个数字,这也可以是每个 id 的平均记录数。如何获得平均值?

最佳答案

在访问 groupby 元素时,我们可以将 reindexrange(3) 结合使用。之后,我们sort_values并将NaN设置为第一个位置,这样我们就可以fillna为0。

df_new = pd.concat([
d[['id', 'temperature']].reset_index(drop=True).reindex(range(3)).sort_values('id', na_position='first')
for _, d in df.groupby('id')
], ignore_index=True)

df_new['id'].fillna(method='bfill', inplace=True)
df_new['temperature'].fillna(0, inplace=True)

print(df_new)
id temperature
0 1.0 12.0
1 1.0 12.0
2 1.0 12.0
3 2.0 0.0
4 2.0 0.0
5 2.0 15.0
6 3.0 0.0
7 3.0 15.0
8 3.0 15.0

注意您有 iddate 作为索引,因此首先运行:

df.reset_index(inplace=True)

关于python - 修复 Pandas 中的 Groupby 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737773/

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