如何比较pandas数据帧中第二列的值和第一列的相同值?

2024-05-19 20:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何针对同一数据帧中第一列的所有相同值提取和比较数据帧中第二列的值?在

我有一个数据框叫“df”:

Name         Datetime
Bob          26-04-2018 12:00:00
Claire       26-04-2018 12:00:00
Bob          26-04-2018 12:30:00
Grace        27-04-2018 08:30:00
Bob          27-04-2018 09:30:00

我想在数据框中添加一个新的列df['Id'],这样,对于具有相同名称的用户,如果日期时间值的差异不超过30分钟,则将为他们分配相同的Id值,如果日期时间差大于30分钟,则将为其分配一个不同的Id

我认为可以通过循环迭代来实现,但我不确定如何实现。另外,有没有更好的方法来做这个,因为我有一个庞大的数据集?在

我预期的数据帧输出如下:

^{pr2}$

任何帮助都将不胜感激。 谢谢


Tags: 数据方法用户name名称iddfdatetime
2条回答

我认为使用groupbygrouper和{}很简单,如下所示:

df['Id'] = df.groupby([pd.Grouper(freq='30T', key='Datetime'), 'Name']).ngroup().add(1)


Out[423]:
     Name            Datetime  Id
0     Bob 2018-04-26 12:00:00   1
1  Claire 2018-04-26 12:00:00   2
2     Bob 2018-04-26 12:10:00   1
3     Bob 2018-04-26 12:20:00   1
4  Claire 2018-04-27 08:30:00   3
5     Bob 2018-04-27 09:30:00   4

我将按名称、日期时间对数据帧进行排序,以标识不同的组,然后按原始数据帧顺序为每个组分配一个Id值。在

代码可以是:

# sort data frame on Name and datetime
df.sort_values(['Name', 'Datetime'], inplace=True)
df1 = df.shift()
# identify new Ids
df.loc[(df1.Name!=df.Name)
       |(df.Datetime-df1.Datetime>pd.Timedelta(minutes=30)), 'tmp'] = 1
del df1   # non longer usefull

# ok, one different tmp value for each group
df['tmp'] = df['tmp'].cumsum().ffill()

# compute Ids in original dataframe orders
ids = pd.DataFrame(df['tmp'].drop_duplicates().sort_index())
ids['Id'] = ids.reset_index(drop=True).index + 1

# and get the expected result
df = df.reset_index().merge(ids, on='tmp').set_index('index').sort_index()\
     .drop(columns='tmp').rename_axis(None)

正如预期的那样:

^{pr2}$

相关问题 更多 >