将熊猫列四舍五入到年份



Python和Pandas初学者。

我想把pandas数据帧列四舍五入到年。7月1日之前的日期必须四舍五入到当年,7月1号之后和当天的日期必须向上取整到下一年。

例如:

2011-04-05必须四舍五入为2011

2011-08-09必须四舍五入为2012

2011-06-30必须四舍五入为2011

2011-07-01必须四舍五入为2012

我尝试过的:

pd.series.dt.round(freq='Y')

给出错误:ValueError: <YearEnd: month=12> is a non-fixed frequency

数据帧列有各种各样的日期,从1945年一直到2021年。因此,简单的CCD_ 11不起作用。

我也尝试了dt.to_period('Y')函数,但无法给出七月一日之前和之后的参数。

关于如何解决这个问题,有什么建议吗?

假设您有以下数据帧:

dates
0 2011-04-05
1 2011-08-09
2 2011-06-30
3 2011-07-01
4 1945-06-30
5 1945-07-01

然后:

# convert to datetime:
df["dates"] = pd.to_datetime(df["dates"])
df["year"] = np.where(
(df["dates"].dt.month < 7), df["dates"].dt.year, df["dates"].dt.year + 1
)
print(df)

打印:

dates  year
0 2011-04-05  2011
1 2011-08-09  2012
2 2011-06-30  2011
3 2011-07-01  2012
4 1945-06-30  1945
5 1945-07-01  1946

一个迂回的年份是将日期值转换为字符串,将它们分离,然后在循环中对它们进行分类,如下所示:

for i in df["Date"]: # assuming the column's name is "Date"
thisdate = df["Date"] # extract the ith element of Date
thisdate = str(thisdate) # convert to string
datesplit = thisdate.split("-") # split
Yr = int(datesplit[0]) # get the year # convert year back to a number
Mth = int(datesplit[1]) # get the month # convert month back to a number
if Mth < 7: # any date before July
rnd_Yr = Yr
else: # any date after July 1st
rnd_Yr = Yr + 1

最新更新