[英]pandas dataframe sort by date
我通過導入一個 csv 文件制作了一個數據框。 並將日期列轉換為日期時間並使其成為索引。 但是,在對索引進行排序時,它不會產生我想要的結果
print(df.head())
df['Date'] = pd.to_datetime(df['Date'])
df.index = df['Date']
del df['Date']
df.sort_index()
print(df.head())
結果如下:
Date Last
0 2016-12-30 1.05550
1 2016-12-29 1.05275
2 2016-12-28 1.04610
3 2016-12-27 1.05015
4 2016-12-23 1.05005
Last
Date
2016-12-30 1.05550
2016-12-29 1.05275
2016-12-28 1.04610
2016-12-27 1.05015
2016-12-23 1.05005
日期實際上可以追溯到 1999 年,所以如果我按日期排序,它應該按升序顯示數據對嗎?
只是擴展 MaxU 的正確答案:您使用了正確的方法,但是,就像許多其他 Pandas 方法一樣,您必須“重新創建”數據框以使所需的更改生效。 正如 MaxU 已經建議的那樣,這是通過再次鍵入變量來實現的(將所用方法的輸出“存儲”到同一變量中),例如:
df = df.sort_index()
或者通過利用屬性inplace=True
的力量,它將替換變量的內容而無需重新聲明它。
df.sort_index(inplace=True)
但是,根據我的經驗,我經常覺得使用第一個選項“更安全”。 它看起來也更清晰、更規范,因為並非所有方法都提供inplace
使用。 但我都歸結為腳本風格,我想......
數據看起來像這樣
Date,Last
2016-12-30,1.05550
2016-12-29,1.05275
2016-12-28,1.04610
2016-12-27,1.05015
2016-12-23,1.05005
使用pandas讀取數據
import pandas as pd
df = pd.read_csv('data',sep=',')
# Displays the data head
print (df.head())
Date Last
0 2016-12-30 1.05550
1 2016-12-29 1.05275
2 2016-12-28 1.04610
3 2016-12-27 1.05015
4 2016-12-23 1.05005
# Sort column with name Date
df = df.sort_values(by = 'Date')
Date Last
4 2016-12-23 1.05005
3 2016-12-27 1.05015
2 2016-12-28 1.04610
1 2016-12-29 1.05275
0 2016-12-30 1.05550
# reset the index
df.reset_index(inplace=True)
# Display the data head after index reset
index Date Last
0 4 2016-12-23 1.05005
1 3 2016-12-27 1.05015
2 2 2016-12-28 1.04610
3 1 2016-12-29 1.05275
4 0 2016-12-30 1.05550
# delete the index
del df['index']
# Display the data head
print (df.head())
Date Last
0 2016-12-23 1.05005
1 2016-12-27 1.05015
2 2016-12-28 1.04610
3 2016-12-29 1.05275
4 2016-12-30 1.05550
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.