简体   繁体   English

如何使用 Pandas/in Python 重新格式化索引中的日期

[英]How to reformat dates in an index using Pandas/in Python

My variable dates_city stores this:我的变量dates_city存储这个:

Index(['2020-11-17T00:00:00', '2020-11-18T00:00:00', '2020-11-19T00:00:00',
       '2020-11-20T00:00:00', '2020-11-21T00:00:00', '2020-11-22T00:00:00',
       '2020-11-23T00:00:00', '2020-11-24T00:00:00', '2020-11-25T00:00:00',
       '2020-11-26T00:00:00', '2020-11-27T00:00:00', '2020-11-28T00:00:00'])

I want it to be stored as:我希望它存储为:

Index(['2020-11-17', '2020-11-18', '2020-11-19',
       '2020-11-20', '2020-11-21', '2020-11-22',
       '2020-11-23', '2020-11-24', '2020-11-25',
       '2020-11-26', '2020-11-27', '2020-11-28'])

So, basically with just the date in yyyy-mm-dd format.所以,基本上只有 yyyy-mm-dd 格式的日期。 I was trying to use datetime but I can't seem to get it to work, possibly because this variable is an index, not an array.我试图使用 datetime 但我似乎无法让它工作,可能是因为这个变量是一个索引,而不是一个数组。 How do I reformat this?我该如何重新格式化?

You could change the index of your dataframe using pandas reset_index() method.您可以使用 pandas reset_index()方法更改 dataframe 的索引。 Note that this will rename the date column to 'index', so you may want to rename it using pandas rename() method.请注意,这会将日期列重命名为“索引”,因此您可能希望使用 pandas rename()方法对其进行重命名。

Then you can use pandas strftime() method to reformat your dates.然后您可以使用 pandas strftime()方法重新格式化您的日期。 After reformatting, if you still want to use the date column as the index, you can do that by changing the index attribute of the dataframe (see code below):重新格式化后,如果仍想使用日期列作为索引,可以通过更改 dataframe 的索引属性来实现(见下面的代码):

df.index = df['Date']

pandas.to_datetime worked for me: pandas.to_datetime为我工作:

pd.to_datetime(dates_city)
#DatetimeIndex(['2020-11-17', '2020-11-18', '2020-11-19', '2020-11-20',
#               '2020-11-21', '2020-11-22', '2020-11-23', '2020-11-24',
#               '2020-11-25', '2020-11-26', '2020-11-27', '2020-11-28'],
#              dtype='datetime64[ns]', freq=None)

If you want to keep it as pandas.Index , you can add the method pandas.DatetimeIndex.strftime :如果要将其保留为pandas.Index ,可以添加方法pandas.DatetimeIndex.strftime

pd.to_datetime(dates_city).strftime("%Y-%m-%d")
#Index(['2020-11-17', '2020-11-18', '2020-11-19', '2020-11-20', '2020-11-21',
#       '2020-11-22', '2020-11-23', '2020-11-24', '2020-11-25', '2020-11-26',
#       '2020-11-27', '2020-11-28'],
#      dtype='object')

You can find the datetime format codes here .您可以在此处找到日期时间格式代码。

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

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