有没有一种方法可以根据熊猫中的唯一值对列进行排序?

时间:2020-07-01 07:24:03

标签: pandas dataframe pandas-groupby unique

假设我有一个具有日期和ID列的数据框。这是一个时间序列数据集。所以我需要为此数据帧生成一个时间序列标识符。也就是说,我需要添加一个与每个唯一集合相对应的值。有办法吗?

df = pd.DataFrame({'Date':[2012-01-01, 2012-01-01, 2012-01-01, 2012-01-02, 2012-01-02, 2012-01-03, 2012-01-03, 2012-01-03, 2012-01-04, 2012-01-01, 2012-01-04],
                      'Id':[1,2,3,4,5,6,7,8,9,10,11]})
print(df)

输出:

   Date       Id
2012-01-01     1
2012-01-01     2
2012-01-01     3
2012-01-02     4
2012-01-02     5
2012-01-03     6
2012-01-03     7
2012-01-03     8
2012-01-04     9
2012-01-01     10
2012-01-04     11

我需要根据日期的唯一性来订购日期

   Date       Id      TimeID
2012-01-01     1         0
2012-01-02     4         0
2012-01-03     6         0
2012-01-04     9         0
2012-01-01     2         1
2012-01-02     5         1
2012-01-03     7         1
2012-01-04     11        1
2012-01-01     3         2
2012-01-03     8         2
2012-01-01     10        3

2 个答案:

答案 0 :(得分:2)

GroupBy.cumcountDataFrame.sort_values一起使用:

df['TimeID'] = df.groupby('Date').cumcount()
df = df.sort_values('TimeID')
print (df)
          Date  Id  TimeID
0   2012-01-01   1       0
3   2012-01-02   4       0
5   2012-01-03   6       0
8   2012-01-04   9       0
1   2012-01-01   2       1
4   2012-01-02   5       1
6   2012-01-03   7       1
10  2012-01-04  11       1
2   2012-01-01   3       2
7   2012-01-03   8       2
9   2012-01-01  10       3

答案 1 :(得分:0)

首先,使用pd.to_datetime()将字符串日期转换为日期时间。 然后,按照this solution使用groupby().cumcount()

import pandas as pd
  
df = pd.DataFrame({'Date': ['2012-01-01','2012-01-01','2012-01-01','2012-01-02',
        '2012-01-02','2012-01-03','2012-01-03','2012-01-03','2012-01-04','2012-01-01','2012-01-04'],
        'Id': [1,2,3,4,5,6,7,8,9,10,11]})

# strictly, you can read in a datetime as a datetime at pd.read_csv() time
df['Date'] = pd.to_datetime(df['Date'])