![](/img/trans.png)
[英]fill the column with the sum of the values from the other column in the specified interval in pandas
[英]Pandas sum column based on window interval of other column
有一个像这样的 df:
weight timeblock
1 1620975600
1 1620975640
1 1620975700
1 1620975715
1 1620975740
1 1620975790
1 1620975800
我想根据时间块间隔的 45 秒间隔对权重列求和,使其看起来像:
weight interval
2 1620975600
2 1620975690
1 1620975735
2 1620975780
其中,间隔列表示从那时开始的 45 秒时间间隔。
我将如何执行此操作并跳过时间块不存在的 45 秒间隔?
您可以使用pd.cut
以 45 秒的增量创建垃圾箱,然后按垃圾箱pd.cut
并获取大小并删除零计数。
import pandas as pd
df = pd.DataFrame({'weight': [1, 1, 1, 1, 1, 1, 1],
'timeblock': [1620975600,
1620975640,
1620975700,
1620975715,
1620975740,
1620975790,
1620975800]})
df['interval'] = pd.cut(df.timeblock,
bins=[x for x in range(df.timeblock.min(), df.timeblock.max()+45, 45)],
labels=[x for x in range(df.timeblock.min(), df.timeblock.max(), 45)],
include_lowest=True)
df = df.groupby('interval').size().reset_index(name='weight')
df.loc[df['weight']>0]
输出
interval weight
0 1620975600 2
2 1620975690 2
3 1620975735 1
4 1620975780 2
不知道为什么他们删除了他们的评论,但这似乎有效:
df = df.groupby(df.timeblock // 45).weight.sum().reset_index()
df['timeblock'] = df['timeblock'].apply(lambda x: x*45)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.