简体   繁体   English

如何使用 Pandas/Python 在特定列中的每个项目行上使用 function

[英]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.连同您的申请线。

You probably want to use apply() method of the pandas dataframe:您可能想使用 pandas dataframe 的apply()方法:

df['Weekday'] = df['Date'].apply(convert_date_to_weekday)

But your convert_date_to_weekday should return the result instead of printing.但是您的convert_date_to_weekday应该返回结果而不是打印。

You can use the apply() function.您可以使用apply() function。

df['Weekday'] = df['Date'].apply(lambda d: convert_date_to_weekday(d))

Also, change your print(date_object.strftime("%A")) to return date_object.strftime("%A")另外,更改您的print(date_object.strftime("%A"))return date_object.strftime("%A")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM