2017-09-16 49 views
1

我在python数据框中有日期列。我想通过订购日期来索引这些内容。这在Python中是可能的吗?如何索引python中的日期列

date  indexed 
2007-02-21 3 
2007-02-18 1 
2007-02-24 5 
2007-02-18 1 
2007-02-23 4 
2007-02-20 2 
2007-02-23 4 

我正在寻找索引,但我想我使用错误的术语来检查。请指导。

编辑

其实我想用相当于索引号更换日期。

+0

是的,你需要按日期对它们进行排序,该索引之后他们都使用一个简单的循环 –

+0

[排序数据帧后更新索引]的可能重复(https://stackoverflow.com/questions/33165734/update-index-after-sorting-data-frame) –

+0

'df.sort_values(by ='日期')' – mwweb

回答

1

IIUC要使用pd.factorize()方法sort_values:

In [190]: df['new'] = pd.factorize(df['date'], sort=True)[0] + 1 

In [191]: df 
Out[191]: 
     date indexed new 
0 2007-02-21  3 3 
1 2007-02-18  1 1 
2 2007-02-24  5 5 
3 2007-02-18  1 1 
4 2007-02-23  4 4 
5 2007-02-20  2 2 
6 2007-02-23  4 4 

PS pd.factorize()开始从0算起,所以我加入1,以满足您的期望的结果

+0

非常感谢。为什么我们在这里加1?请澄清 –

+0

@DoubtDhanabalu,'pd.factorize()'从'0'开始。所以我已经加了'1'为了达到你想要的效果 – MaxU

+0

好吧,我明白了,非常感谢。我接受这个答案。再次感谢。 –

1

你所寻找的是按日期

df = pd.DataFrame(["2007-02-21","2007-02-18","2007-02-24","2007-02-18","2007-02-23","2007-02-20","2007-02-23"],columns=["date"]) 

enter image description here

df.sort_values("date", axis=0) 

enter image description here

1

使用pandas.DataFrame.sort_index

import pandas as pd 

df = pd.DataFrame(['2007-02-21','2007-02-18','2007-02-24','2007-02-18','2007- 
02-23', '2007-02-20' , '2007-02-23'], index=[3, 1, 5, 1, 4,2,4], columns= 
['Date']) 

print df 
     Date 
3 2007-02-21 
1 2007-02-18 
5 2007-02-24 
1 2007-02-18 
4 2007-02-23 
2 2007-02-20 
4 2007-02-23 


df2 = df.sort_index(axis=0) 
print(df2) 

     Date 
1 2007-02-18 
1 2007-02-18 
2 2007-02-20 
3 2007-02-21 
4 2007-02-23 
4 2007-02-23 
5 2007-02-24