简体   繁体   English

数据框 set_index 未设置

[英]Dataframe set_index not setting

I have a dataframe and am trying to set the index to the column 'Timestamp'.我有一个数据框,正在尝试将索引设置为“时间戳”列。 Currently the index is just a row number.目前索引只是一个行号。 An example of Timestamp's format is: 2015-09-03 16:35:00 Timestamp 的格式示例为: 2015-09-03 16:35:00

I've tried to set the index:我试图设置索引:

df.set_index('Timestamp')

I don't get an error, but when I print the dataframe, the index is still the row number.我没有收到错误,但是当我打印数据框时,索引仍然是行号。 How can I use Timestamp as the index?如何使用时间戳作为索引?

You need to either specify inplace=True , or assign the result to a variable.您需要指定inplace=True ,或将结果分配给变量。 Try:尝试:

df.set_index('Timestamp', inplace=True, drop=True)

Basically, there are two things that you might want to do when you set the index.基本上,设置索引时可能需要做两件事。 One is new_df = old_df.set_index('Timestamp', inplace=False) .一个是new_df = old_df.set_index('Timestamp', inplace=False) Ie You want a new DataFrame that has the new index, but still want a copy of the original DataFrame.即,您想要一个具有新索引的新 DataFrame,但仍想要原始 DataFrame 的副本。 The other is df.set_index('Timestamp', inplace=True) .另一个是df.set_index('Timestamp', inplace=True) Which is for when you want to modify the existing object.当您想要修改现有对象时。

To add to the accepted answer: Remember that you might need to set your timestamp into a datetime!要添加到已接受的答案:请记住,您可能需要将时间戳设置为日期时间!

df = pd.read_csv(dataFile)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index("timestamp", inplace=True, drop=True)
df.info()

References: https://www.geeksforgeeks.org/python-pandas-dataframe-set_index/ how set column as date index?参考资料: https ://www.geeksforgeeks.org/python-pandas-dataframe-set_index/ 如何将列设置为日期索引?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM