我有一个包含年,月,日字段的df,格式为整数。我使用以下内容提取星期几。
我该如何更精巧地做到这一点?
### First Attempt - Succeeds
lst = []
for i in zip(df['day'], df['month'], df['year']):
lst.append(calendar.weekday(i[2], i[1], i[0]))
df['weekday'] = lst
### Second Attempt -- Fails
df['weekday'] = df.apply(lambda x: calendar.weekday(x.year, x.month, x.day))
AttributeError: ("'Series' object has no attribute 'year'", 'occurred at index cons_conf')
答案 0 :(得分:1)
尝试使用.to_datetime
和dt
访问器:
import pandas as pd
data = pd.DataFrame({'year': [2018, 2018, 2018], 'month': [12, 12, 12], 'day': [1, 2, 3]})
data['weekday'] = pd.to_datetime(data[['year', 'month', 'day']]).dt.weekday
print(data)
给予:
year month day weekday
0 2018 12 1 5
1 2018 12 2 6
2 2018 12 3 0
请注意,工作日的索引为零。