pandas 如何在Python中将不同的数据类型格式化为dd/mm/yyyy格式

nqwrtyyt  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(105)

我有一个代码,我想将所有的日期列更改为dd/mm/yyyy格式。日期列中传递的所有值都已经是这种格式,即使是第二个值:01/02/2001,其中我想显示为日:01,月:02(二月),年份:2001.
我怎样才能让我的代码改变这种类型的值?
我在Chatgpt上搜索,但他们回复的代码不起作用。
我的代码:

import pandas as pd

data = {
    'Date': ['01/01/01', '01-02-2001', 'March 1rd, 2001'],    
    'Name': ['Ana', 'Bob', 'Carl']
}
df_data = pd.DataFrame(data)

# Change to datetime data type
df_data['Date'] = pd.to_datetime(df_data['Date'])

# Change the Date format to dd/mm/yyyy
df_data['Date'] = df_data['Date'].dt.strftime("%d/%m/%Y")

输出:

Date  Name
0  01/01/2001   Ana
1  02/01/2001   Bob
2  01/03/2001  Carl

预期输出:

Date  Name
0  01/01/2001   Ana
1  01/02/2001   Bob
2  01/03/2001  Carl

ChatGpt响应:

import pandas as pd

# Create a sample dataframe with dates in different formats
data = {'Date': ['2022-01-01', '01-02-2022', '01/03/2022', '2022/04/01', '01-Apr-2022'], 'Name': ['Ana', 'Bob', 'Carl', 'Dave', 'Emma']}
df = pd.DataFrame(data)

# Define the possible date formats
date_formats = ["%Y-%m-%d", "%d-%m-%Y", "%m/%d/%Y", "%d/%m/%Y", "%d-%b-%Y"]

# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'], format=date_formats, errors='coerce')

print(df)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-1c5d1f56aa15> in <cell line: 11>()
      9 
     10 # Convert the 'Date' column to datetime format
---> 11 df['Date'] = pd.to_datetime(df['Date'], format=date_formats, errors='coerce')
     12 
     13 print(df)

1 frames
/usr/local/lib/python3.9/dist-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    386         # format because this path makes process slower in this
    387         # special case
--> 388         format_is_iso8601 = format_is_iso(format)
    389         if format_is_iso8601:
    390             require_iso8601 = not infer_datetime_format

TypeError: Argument 'f' has incorrect type (expected str, got list)
yr9zkbsy

yr9zkbsy1#

dayfirst=True参数添加到to_datetime()

df_data['Date'] = (pd.to_datetime(df_data['Date'], dayfirst=True, errors='coerce')
                     .dt.strftime('%d/%m/%Y')) 
print(df_data)
Date  Name
0  01/01/2001   Ana
1  01/02/2001   Bob
2  01/03/2001  Carl

相关问题