Python 熊猫-在一系列时间戳中查找时间序列发生的顺序
我在df中有一系列日期,希望能够通过创建一个新列(即…发生在系列值中的第一个,第二个…第三个…第4000个…最后一个)找到每个日期发生的顺序Python 熊猫-在一系列时间戳中查找时间序列发生的顺序,python,python-3.x,pandas,Python,Python 3.x,Pandas,我在df中有一系列日期,希望能够通过创建一个新列(即…发生在系列值中的第一个,第二个…第三个…第4000个…最后一个)找到每个日期发生的顺序 0 2016-01-27 16:37:17 1 2015-11-08 13:54:15 2 2015-06-15 22:17:25 3 2015-06-18 10:47:01 4 2015-01-06 18:42:23 5 2015-06-19 15:05:21 6 2015
0 2016-01-27 16:37:17
1 2015-11-08 13:54:15
2 2015-06-15 22:17:25
3 2015-06-18 10:47:01
4 2015-01-06 18:42:23
5 2015-06-19 15:05:21
6 2015-12-06 10:41:59
....
5769 2011-03-24 11:42:24
5770 2010-01-14 09:51:24
5771 2010-01-13 14:30:28
5772 2010-04-29 10:44:22
5773 2010-01-14 10:31:26
5774 2010-11-22 16:10:22
5775 2010-08-07 11:45:14
Name: CreationTime, Length: 5776, dtype: datetime64[ns]
如何在熊猫身上做到这一点?这里有一种方法:
import pandas as pd
import numpy as np
# Create sample data
data = dict(dates=pd.date_range(start="2017-12-01", end="2017-12-15"))
# Make it a dataframe, resample and reset index
df = pd.DataFrame(data).sample(frac=1).reset_index(drop=True)
# Get id by using map with sorted column
df['idx'] = df.dates.map(dict(zip(sorted(df.dates),range(len(df)))))
print(df)
样本返回:
dates idx
0 2017-12-08 7
1 2017-12-10 9
2 2017-12-09 8
3 2017-12-01 0
4 2017-12-04 3
5 2017-12-07 6
6 2017-12-03 2
7 2017-12-05 4
8 2017-12-11 10
9 2017-12-14 13
10 2017-12-15 14
11 2017-12-12 11
12 2017-12-02 1
13 2017-12-06 5
14 2017-12-13 12
按创建时间排序,然后复制索引
df = df.sort_values(by=['creation_time'])
df['rank'] = df.reset_index().index
您只需对_值['CreationTime']进行排序,然后重置_索引,索引的值将按日期时间顺序从0到5775。这将返回它们出现的ID,而不是它们出现的ID。谢谢。似乎这种方法的开始日期和结束日期必须是已知的?在我的数据集中并不总是这样。你能绕过这个吗?@Stewart不,这只是一个可验证的例子。您只需输入idx行并将.date更改为[“创建时间”]