计算数据帧中具有分钟差异的连续行
Count consecutive rows with minutes difference in dataframe
5我有一个如下所示的数据框:
Name
Site
Time
Manual
BCN
3/10/2022 11:23:13 PM
Manual
BCN
3/10/2022 11:38:47 PM
Automatic
Madrid
3/10/2022 11:40:32 PM
Manual
BCN
3/10/2022 11:39:47 PM
Manual
BCN
3/11/2022 12:44:47 AM
它由名称列、地点和时间组成。我正在寻找的是计算名称和地点相等且实例之间的时间少于 20 分钟的位置。在这种情况下,输出将是 Manual,bcn1 ->3 倍,因为第 5 行与其他两行相距一个小时。数据按时间排序。
我尝试过使用名称和地点进行分组,然后对时间应用差异,但无济于事。
df['Time'] = pd.to_datetime(df['Time'])
g=( df.groupby(['site','Name'])['Time'].diff().ne(pd.Timedelta(minutes=20))
.groupby(df['site','Ppath']).cumsum() )
groups = df.groupby(['Site',g])['Time']
new_df = df.assign(count = groups.transform('size'))
这将返回所有值的计数,而不是满足时间增量的值。文件本身很大,有多个名称和站点。
非常感谢
编辑1。
为了澄清,我正在查看值对,因此在本例中是第一行和第二行。然后是第二个和第三个,依此类推。我正在探索一种按名称和站点过滤的解决方案。
谢谢
IIUC,尝试:
df["Time"] = pd.to_datetime(df["Time"])
df = df.sort_values("Time", ignore_index=True)
output = (df.groupby(["Name", "Site"])["Time"].apply(lambda x: x.diff()
.dt
.total_seconds()
.div(60)
.fillna(0)
.le(20)
.sum()
)
)
>>> output
Name Site
Automatic Madrid 1
Manual BCN 3
Name: Time, dtype: int64
5我有一个如下所示的数据框:
Name | Site | Time |
---|---|---|
Manual | BCN | 3/10/2022 11:23:13 PM |
Manual | BCN | 3/10/2022 11:38:47 PM |
Automatic | Madrid | 3/10/2022 11:40:32 PM |
Manual | BCN | 3/10/2022 11:39:47 PM |
Manual | BCN | 3/11/2022 12:44:47 AM |
它由名称列、地点和时间组成。我正在寻找的是计算名称和地点相等且实例之间的时间少于 20 分钟的位置。在这种情况下,输出将是 Manual,bcn1 ->3 倍,因为第 5 行与其他两行相距一个小时。数据按时间排序。
我尝试过使用名称和地点进行分组,然后对时间应用差异,但无济于事。
df['Time'] = pd.to_datetime(df['Time'])
g=( df.groupby(['site','Name'])['Time'].diff().ne(pd.Timedelta(minutes=20))
.groupby(df['site','Ppath']).cumsum() )
groups = df.groupby(['Site',g])['Time']
new_df = df.assign(count = groups.transform('size'))
这将返回所有值的计数,而不是满足时间增量的值。文件本身很大,有多个名称和站点。
非常感谢
编辑1。 为了澄清,我正在查看值对,因此在本例中是第一行和第二行。然后是第二个和第三个,依此类推。我正在探索一种按名称和站点过滤的解决方案。
谢谢
IIUC,尝试:
df["Time"] = pd.to_datetime(df["Time"])
df = df.sort_values("Time", ignore_index=True)
output = (df.groupby(["Name", "Site"])["Time"].apply(lambda x: x.diff()
.dt
.total_seconds()
.div(60)
.fillna(0)
.le(20)
.sum()
)
)
>>> output
Name Site
Automatic Madrid 1
Manual BCN 3
Name: Time, dtype: int64