我通过导入csv文件制作了一个数据帧。并将date列转换为datetime并使其成为索引。然而,在对索引进行排序时,它并没有产生我想要的结果
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年,所以如果我按日期排序,它应该以升序显示数据,对吧?
发布于 2017-01-03 20:38:50
只需扩展MaxU的正确答案:您使用了正确的方法,但是,就像许多其他pandas方法一样,您必须“重新创建”dataframe才能使所需的更改生效。正如MaxU已经建议的,这是通过再次键入变量来实现的(将使用的方法的输出“存储”到相同的变量中),例如:
df = df.sort_index()
或者利用属性inplace=True
的功能,它将替换变量的内容,而不需要重新声明它。
df.sort_index(inplace=True)
然而,在我的经验中,我经常觉得使用第一个选项“更安全”。它看起来也更清晰、更规范化,因为并不是所有的方法都提供inplace
用法。但我想我都归结为脚本系统了。
发布于 2018-10-18 06:43:16
数据如下所示
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
https://stackoverflow.com/questions/41433765
复制相似问题