[英]How to use function on every item row in specific column with Pandas/Python
I have a simple DataFrame in Pandas that one of the column contains date in this format day-month-year.我在 Pandas 中有一个简单的 DataFrame ,其中一列包含这种格式的日期 - 月 - 年。 I need to make another column that contains which weekday is that.
我需要制作另一列,其中包含那是哪个工作日。 I wrote this function that works with simple argument like '12-3-1999':
我写了这个 function,它适用于像“12-3-1999”这样的简单参数:
def convert_date_to_weekday(date_string):
# convert string to date object
date_object = datetime.strptime(date_string, '%d-%m-%Y').date()
# convert date object to weekday string
print(date_object.strftime("%A"))
Unfortunetely this doesn't work:不幸的是,这不起作用:
df['Weekday'] = convert_date_to_weekday(df['Date'])
How to make it work?如何让它发挥作用?
You can use apply , which also a recommended way with pandas您可以使用apply ,这也是 pandas 的推荐方式
def convert_date_to_weekday(date_string):
# convert string to date object
date_object = datetime.strptime(date_string, '%d-%m-%Y').date()
# convert date object to weekday string
# print(date_object.strftime("%A"))
return date_object.strftime("%A")
df['Weekday'] = df['Date'].apply(lambda x: convert_date_to_weekday(x)))
try尝试
df['Weekday'] = df['Date'].apply(lambda x: convert_date_to_weekday(x))
and use return in your function instead of print并在您的 function 中使用 return 而不是 print
Try:尝试:
def convert_date_to_weekday(date_string):
# convert string to date object
date_object = datetime.strptime(date_string, '%d-%m-%Y').date()
# convert date object to weekday string
return date_object.strftime("%A")
Along with your apply line.连同您的申请线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.