2017-09-16 47 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