分组并插入 Pandas
Groupby and interpolate in Pandas
我的数据包含周数、帐户 ID 和多个使用列。我想 a) 按帐户 ID 分组,b) 将每周数据重新采样为每日数据,c) 平均插入每日数据(将每周数据除以 7),然后将它们全部放回一起。我已经记下了大部分内容,但是 Pandas groupby
让我有点困惑。它也很慢,这让我觉得这可能不是最佳解决方案。
数据如下所示:
Account Id year week views stats foo_col
31133 213 2017-03-05 4.0 2.0 11.0
10085 456 2017-03-12 1.0 6.0 3.0
49551 789 2017-03-26 1.0 6.0 27.0
这是我的代码:
def interpolator(mini_df):
mini_df = mini_df[cols_to_interpolate].set_index('year week')
return mini_df.resample('D').ffill().interpolate() / 7
example = list(grp)[0][1]
interpolator(example) # This works perfectly
df.groupby('Account Id').agg(interpolator) # doesn't work
df.groupby('Account Id').transform(interpolator) # doesn't work
for name,group in grp:
group = group[cols_to_interpolate].set_index('year week')
group = group.resample('D').ffill().interpolate() / 7 # doesn't work
for acc_id in df['Account Id'].unique():
mask = df.loc[df['Account Id'] == acc_id]
print(df[mask]) # doesn't work
我希望您的函数应该与 groupby
对象链接,例如:
df = (df.set_index('year week')
.groupby('Account Id')[cols_to_interpolate]
.resample('D')
.ffill()
.interpolate() / 7)
来自评论的解决方案不同 - interpolate
适用于每个组:
df.groupby('Account Id').apply(interpolator)
我的数据包含周数、帐户 ID 和多个使用列。我想 a) 按帐户 ID 分组,b) 将每周数据重新采样为每日数据,c) 平均插入每日数据(将每周数据除以 7),然后将它们全部放回一起。我已经记下了大部分内容,但是 Pandas groupby
让我有点困惑。它也很慢,这让我觉得这可能不是最佳解决方案。
数据如下所示:
Account Id year week views stats foo_col
31133 213 2017-03-05 4.0 2.0 11.0
10085 456 2017-03-12 1.0 6.0 3.0
49551 789 2017-03-26 1.0 6.0 27.0
这是我的代码:
def interpolator(mini_df):
mini_df = mini_df[cols_to_interpolate].set_index('year week')
return mini_df.resample('D').ffill().interpolate() / 7
example = list(grp)[0][1]
interpolator(example) # This works perfectly
df.groupby('Account Id').agg(interpolator) # doesn't work
df.groupby('Account Id').transform(interpolator) # doesn't work
for name,group in grp:
group = group[cols_to_interpolate].set_index('year week')
group = group.resample('D').ffill().interpolate() / 7 # doesn't work
for acc_id in df['Account Id'].unique():
mask = df.loc[df['Account Id'] == acc_id]
print(df[mask]) # doesn't work
我希望您的函数应该与 groupby
对象链接,例如:
df = (df.set_index('year week')
.groupby('Account Id')[cols_to_interpolate]
.resample('D')
.ffill()
.interpolate() / 7)
来自评论的解决方案不同 - interpolate
适用于每个组:
df.groupby('Account Id').apply(interpolator)