如何设置一个等于一个月和一天的变量,然后用它做数学?

问题描述 投票:0回答:1

我在Python中使用pandas数据帧。数据框包含4列。我在这里工作的专栏是年份和收获。年份是特定事件发生的年份,收获是事件发生的8月31日之前的天数。所以基本上,如果收获等于23,则该事件发生在该年的9月23日。

我被要求找到具体的数据集早期收获的时间。作为参考,我的数据框标题为“MyData”。所以我首先定义了最早的年份,如下:

Earliest = MyData.loc[MyData['year'].idxmin()]

现在我不确定如何使用'harvest'变量来返回特定日期(只有几个月和几天)。

我试图定义一个8/31的基本日期变量,然后只添加该基准日期的'harvest'变量。这就是我现在的路线:

BaseDate = pd.to_datetime("08/31",format="%m/%d")

然而,这比我想要的还要多。我只想让它返回08/31。然后,我会使用该BaseDate变量执行以下操作:

print("The harvest happened on", BaseDate + pd.DateOffset(days=Earliest['harvest']),"of that year.")

并且它应该返回类似“收获发生在那年的08/16”。

相反,它目前正在返回以下内容:“收获发生在当年的1900-09-23 00:00:00。”

我可能更好的是在数据框中创建一个全新的列,为每一行进行此数学运算。我愿意接受这样做的解决方案,并且实际上更喜欢它!但就目前而言,我提出它的方式就足够了。

当我尝试创建一个新列时,我将其写出如下:

MyData['Date'] = datetime.datetime(2000,8,31) + MyData['harvest']

要么

MyData['Date'] = BaseDate + MyData['harvest']

但它返回此错误:“+:'datetime.datetime'和'float'”不支持的操作数类型

python pandas date dataframe
1个回答
0
投票

你可以用(BaseDate + pd.DateOffset(days=Earliest['harvest'])).strftime('%m/%d')做到这一点

更新此作品

chk ['newColumn2'] = BaseDate + pd.to_timedelta(chk ['harvest'],unit ='d')

我举了例子

>>> chk = pd.DataFrame({'year':[1700,1701,1702,1703],
...                     'harvest':[42.5,35.9,45.0,49.4]})
>>> 
>>> chk['date']= pd.to_datetime(chk['year'],format='%Y') 
>>> chk['newColumn'] = chk['date'] + pd.to_timedelta(chk['harvest'],unit='d')
>>> chk
   harvest  year                date           newColumn
0     42.5  1700 1700-01-01 00:00:00 1700-02-12 12:00:00
1     35.9  1701 1701-01-01 00:00:00 1701-02-05 21:36:00
2     45.0  1702 1702-01-01 00:00:00 1702-02-15 00:00:00
3     49.4  1703 1703-01-01 00:00:00 1703-02-19 09:36:00

使用我们的BaseDate我们也可以执行

>>> BaseDate = pd.to_datetime("08/31",format="%m/%d")
>>> chk['newColumn2'] = BaseDate + pd.to_timedelta(chk['harvest'],unit='d')
>>> chk
   harvest  year                date           newColumn          newColumn2
0     42.5  1700 1700-01-01 00:00:00 1700-02-12 12:00:00 1900-10-12 12:00:00
1     35.9  1701 1701-01-01 00:00:00 1701-02-05 21:36:00 1900-10-05 21:36:00
2     45.0  1702 1702-01-01 00:00:00 1702-02-15 00:00:00 1900-10-15 00:00:00
3     49.4  1703 1703-01-01 00:00:00 1703-02-19 09:36:00 1900-10-19 09:36:00
© www.soinside.com 2019 - 2024. All rights reserved.