我有一个代码,我想将所有的日期列更改为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)
1条答案
按热度按时间yr9zkbsy1#
将
dayfirst=True
参数添加到to_datetime()