将熊猫列舍入到年份

时间:2021-05-21 10:15:15

标签: python pandas datetime

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 年。因此,简单的 if df.date < 2011-07-01: df['Date']+ pd.offsets.YearBegin(-1) 不起作用。

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

有关如何解决此问题的任何提示?

2 个答案:

答案 0 :(得分:1)

假设你有这个数据框:

       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

答案 1 :(得分:0)

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

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