简体   繁体   English

通过对每个唯一用户进行分组并为每个唯一日期添加访问次数列来对 dataframe 进行排序和排名 Python

[英]Sort and rank a dataframe by grouping each unique user and adding a visit number column for each unique date Python

I am fairly new to Python and I am trying to add a visit number column in a list of users from my data frame.我是 Python 的新手,我正在尝试在我的数据框中的用户列表中添加一个访问编号列。

I have a dataframe of 55 unique users specified by the 'UserID' column and a datetime column indicated by 'dateStarted' I want to create a column that for each user and each unique date there is aa visit number.我有一个 dataframe 的 55 个唯一用户,由“UserID”列和一个由“dateStarted”指示的日期时间列我想创建一个列,为每个用户和每个唯一日期都有一个访问编号。 The dataframe should look like: dataframe 应如下所示:

  UserID dateStarted  visit
0      a    01/01/10      1
1      a    01/01/10      1
2      a    01/04/10      2
3      b    06/02/08      1
4      b    07/15/12      2
5      c    02/12/12      1
6      d    02/12/12      1

Group the dataframe by UserID and rank the values in dateStarted to assign ordinal values.UserID对 dataframe 进行分组,并对rank中的值进行dateStarted以分配序数值。

df['visit'] = df.groupby('UserID')['dateStarted'].rank(method='dense').astype(int)

  UserID dateStarted  visit
0      a    01/01/10      1
1      a    01/01/10      1
2      a    01/04/10      2
3      b    06/02/08      1
4      b    07/15/12      2
5      c    02/12/12      1
6      d    02/12/12      1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每个 Dask Dataframe 列中唯一值的数量 - Number of unique values in each Dask Dataframe column 将唯一列值分组为 pandas dataframe 列中每个唯一值的总和 - Grouping unique column values to sum of each unique value in pandas dataframe column 对唯一列值进行分组以获得 pandas dataframe 列中每个唯一值的平均值 - Grouping unique column values to get average of each unique value in pandas dataframe column 获取每个分组的唯一元素并写入 Pandas Python 中的列 - Get unique elements for each grouping and write to column in Pandas Python 如何排序 dataframe 与列中每个唯一元素的第一次出现? - How to sort a dataframe with the first occurences of each unique element in a column? 使用每年的唯一日期范围在数据框中创建新列 - Create a new column in dataframe using unique date ranges for each year 按每个唯一列值的最近日期过滤 Pandas 数据框 - Filter Pandas dataframe by most recent date for each unique column value Python pandas 按列的唯一值分组 dataframe - Python pandas grouping a dataframe by the unique value of a column Python pandas dataframe:为另一列的每个唯一值查找最大值 - Python pandas dataframe: find max for each unique values of an another column 如何制作 0 和 1 的 dataframe 使得每个唯一值都是一列? - How to make a dataframe of 0 and 1 such that each unique value is a column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM