[英]Using Python's pandas, split the date and select the most recent date
When I attempt to split the date(Ex: Date format: 10/13/2017-10/16/17), take the date after the hyphen, then modify the revised date into standard date format, I receive an error(KeyError: 'Date').当我尝试拆分日期时(例如:日期格式:10/13/2017-10/16/17),取连字符后的日期,然后将修改后的日期修改为标准日期格式,我收到一个错误(KeyError: '日期')。 Below is the code:下面是代码:
import pandas as pd
import datetime as dt
File = pd.read_excel("Hypendata.xlsx")
before_symbol = File["Date"].str.split("-").str[1]
File["Modified data"] = pd.to_datetime(before_symbol["Date"]).dt.strftime("%m/%d/%Y")
File.to_excel("Hypendata.xlsx")
The problem I see is KeyError: "Date."我看到的问题是 KeyError:“日期”。 "Date" is the header in my Excel document. “日期”是我的 Excel 文档中的标题。 I'm not sure why I keep getting this problem.我不知道为什么我一直遇到这个问题。
Could you help me with the code which helps to split the most recent date either it can be before Hypen or after hyphen.您能否帮助我提供有助于拆分最近日期的代码,它可以在连字符之前或连字符之后。 Example: 10/13/2017-10/16/17 In this case most recent date is after hyphen some dataset may have most recent date before hyphen as well.示例:10/13/2017-10/16/17 在这种情况下,最近的日期在连字符之后,某些数据集的最近日期也可能在连字符之前。
Thank you.谢谢你。
before_symbol
is a Series, you don't need access Date
column before_symbol
是一个系列,您不需要访问Date
列
pd.to_datetime(before_symbol).dt.strftime("%m/%d/%Y")
To get the most recent date, you can try要获取最近的日期,您可以尝试
File["Modified data"] = (File["Date"].str.split("-", expand=True)
.apply(pd.to_datetime)
.apply(lambda row: sorted(row)[-1], axis=1)
.dt.strftime("%m/%d/%Y"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.