更改 pandas 列的日期格式(月日年至日月年) [英] Change date format of pandas column (month-day-year to day-month-year)
问题描述
解决了以下问题.
我的熊猫中有一列,其中有一些日期和一些空值.
I have an column in my pandas with some dates and some empty values.
示例:
1 - 3-20-2019
2 -
3 - 2-25-2019
等
我想将格式从month-day-year年转换为day-month-year年,当它为空时,我只想保留它为空.
I want to convert the format from month-day-year to day-month-year, and when its empty, i just want to keep it empty.
最快的方法是什么?
谢谢!
推荐答案
一个人可以使用字符串初始化当天的数据,然后将字符串转换为日期时间.然后,打印件可以按所需格式交付对象.
One can initialize the data for the days using strings, then convert the strings to datetimes. A print can then deliver the objects in the needed format.
我将使用其他格式(以点作为分隔符),以便在步骤之间进行清晰的转换.
I will use an other format (with dots as separators), so that the conversion is clear between the steps.
首先提供示例代码:
import pandas as pd
data = {'day': ['3-20-2019', None, '2-25-2019'] }
df = pd.DataFrame( data )
df['day'] = pd.to_datetime(df['day'])
df['day'] = df['day'].dt.strftime('%d.%m.%Y')
df[ df == 'NaT' ] = ''
对以上内容的评论. df
的第一个实例在ipython解释器中:
Comments on the above.
The first instance of df
is in the ipython interpreter:
In [56]: df['day']
Out[56]:
0 3-20-2019
1 None
2 2-25-2019
Name: day, dtype: object
转换为日期时间后:
In [58]: df['day']
Out[58]:
0 2019-03-20
1 NaT
2 2019-02-25
Name: day, dtype: datetime64[ns]
这样我们就拥有
In [59]: df['day'].dt.strftime('%d.%m.%Y')
Out[59]:
0 20.03.2019
1 NaT
2 25.02.2019
Name: day, dtype: object
那 NaT
出了问题.因此,我们将所有出现的内容替换为空字符串.
That NaT
makes problems. So we replace all its occurrences with the empty string.
In [73]: df[ df=='NaT' ] = ''
In [74]: df
Out[74]:
day
0 20.03.2019
1
2 25.02.2019
这篇关于更改 pandas 列的日期格式(月日年至日月年)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!