【问题标题】:How to set a variable equal to a month and day, and then do math with it?如何设置一个等于月和日的变量,然后用它做数学?
【发布时间】:2019-03-25 01:50:22
【问题描述】:

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

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

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

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

我尝试定义 8/31 的基准日期变量,然后从该基准日期添加“收获”变量。这是我现在的行:

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.")

它应该返回类似“收获发生在当年 8 月 16 日”的内容。

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

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

当我尝试创建一个新专栏时,我将其写成如下:

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

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

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

【问题讨论】:

  • 我想问这个问题的另一种(更简单的)方法是,我怎样才能在这个数据框中添加一个标题为“日期”的列,它只会将“收获”添加到 08/31。

标签: python pandas date dataframe


【解决方案1】:

您可以通过(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

【讨论】:

  • 知道如何在这种格式的日期数据框中添加新列吗?
  • 你可以通过 MyData['newColumn'] = (BaseDate + pd.DateOffset(days=Earliest['harvest'])).strftime('%m/%d')
  • 我收到错误“timedelta days 组件的类型不受支持:系列”
  • @CornelWestside 我们没有使用哪条线,你能附上代码 sn-p
  • MyData['harvest'] 的输出是什么?应该是日期
猜你喜欢
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
相关资源
最近更新 更多