日期格式为 Day
Date format to Day
目前,我的数据框中有一个日期和时间列表 (2017-12-13 01:05:44)。
谁能帮我在我的数据框中创建一个新列('Day'),其中包含与我的日期列相对应的天数列表。
*可以忽略时间。
例如输出:
Date, Day
2017-12-13 01:05:44, Wednesday
2017-12-12 01:02:13, Tuesday
2017-12-11 01:00:55, Monday
2017-12-10 00:59:31, Sunday
2017-12-09 00:58:23, Saturday
如果您将日期作为字符串,则必须将它们转换为日期时间对象
df['Date'] = pd.to_datetime(df['Date'])
你可以使用图层 Series.dt.weekday_name
df['Day'] = df['Date'].dt.weekday_name
参见:timeseries - time date components and pandas.to_datetime()
工作示例
import pandas as pd
data = [
"2017-12-13 01:05:44",
"2017-12-12 01:02:13",
"2017-12-11 01:00:55",
"2017-12-10 00:59:31",
"2017-12-09 00:58:23",
]
# create dataframe
df = pd.DataFrame(data, columns=['Date'])
print('\ntype before:\n', df.dtypes)
# convert strings to datetime
df['Date'] = pd.to_datetime(df['Date'])
print('\ntype after:\n', df.dtypes)
# get weekday name
df['Day'] = df['Date'].dt.weekday_name
print(df)
结果:
type before:
Date object
dtype: object
type after:
Date datetime64[ns]
dtype: object
Date Day
0 2017-12-13 01:05:44 Wednesday
1 2017-12-12 01:02:13 Tuesday
2 2017-12-11 01:00:55 Monday
3 2017-12-10 00:59:31 Sunday
4 2017-12-09 00:58:23 Saturday
目前,我的数据框中有一个日期和时间列表 (2017-12-13 01:05:44)。
谁能帮我在我的数据框中创建一个新列('Day'),其中包含与我的日期列相对应的天数列表。
*可以忽略时间。
例如输出:
Date, Day
2017-12-13 01:05:44, Wednesday
2017-12-12 01:02:13, Tuesday
2017-12-11 01:00:55, Monday
2017-12-10 00:59:31, Sunday
2017-12-09 00:58:23, Saturday
如果您将日期作为字符串,则必须将它们转换为日期时间对象
df['Date'] = pd.to_datetime(df['Date'])
你可以使用图层 Series.dt.weekday_name
df['Day'] = df['Date'].dt.weekday_name
参见:timeseries - time date components and pandas.to_datetime()
工作示例
import pandas as pd
data = [
"2017-12-13 01:05:44",
"2017-12-12 01:02:13",
"2017-12-11 01:00:55",
"2017-12-10 00:59:31",
"2017-12-09 00:58:23",
]
# create dataframe
df = pd.DataFrame(data, columns=['Date'])
print('\ntype before:\n', df.dtypes)
# convert strings to datetime
df['Date'] = pd.to_datetime(df['Date'])
print('\ntype after:\n', df.dtypes)
# get weekday name
df['Day'] = df['Date'].dt.weekday_name
print(df)
结果:
type before:
Date object
dtype: object
type after:
Date datetime64[ns]
dtype: object
Date Day
0 2017-12-13 01:05:44 Wednesday
1 2017-12-12 01:02:13 Tuesday
2 2017-12-11 01:00:55 Monday
3 2017-12-10 00:59:31 Sunday
4 2017-12-09 00:58:23 Saturday