python - 使用日期操作数据框

标签 python date pandas datetime

我有2个数据框如下:

df1:

       id       Grade         Date
1      78        15        2016-05-23
2      99        12        2015-08-01

df2:

                 rate
2015-01-01       1.22
2015-02-01       1.12
   ...
2015-05-01       1.05
2017-01-01       1.33

我想将 df1 中的成绩与同月 df2 中的费率相乘。 因此,对于 2016-05-23,它是在第 05 个月,因为我会将其乘以 1.05。

有什么建议吗? 谢谢您的帮助

最佳答案

如果将 df2 索引设置为每月 PeriodIndex:

In [11]: df2.index = df2.index.to_period("M")

In [12]: df2
Out[12]:
         rate
2015-01  1.22
2015-02  1.12
2016-05  1.32
2015-08  1.23

现在,您可以使用 df2.loc 高效地提取费率:

In [13]: df2.loc[df1.Date.dt.to_period("M")]["rate"]
Out[13]:
2016-05    1.32
2015-08    1.23
Freq: M, Name: rate, dtype: float64

现在,您可以乘以:

In [14]: df2.loc[df1.Date.dt.to_period("M")]["rate"].values * df1["Grade"]
Out[14]:
1    19.80
2    14.76
Name: Grade, dtype: float64


In [21]: df1["NormedGrade"] = df2.loc[df1.Date.dt.to_period("M")]["rate"].values * df1["Grade"]

In [22]: df1
Out[22]:
   id  Grade       Date  Normed Grade
1  78     15 2016-05-23         19.80
2  99     12 2015-08-01         14.76

关于python - 使用日期操作数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43949089/

相关文章:

python - Django聚合外键的最高值

python - 'for x in array' 总是导致排序的 x 吗? [Python/NumPy]

PHP 从开始日期开始有 31 天的距离

java - 使用 SimapleDateFormat 解析时间

python - 在 Python 中生成数据透视表 - Pandas? NumPy ? Xlrd?来自 csv

python - gdb python : How to do arithmetic operation on a gdb. 值?

Python 理解 OOP、继承

r - 将一年添加到 posix 时间

python - VSCODE - PYTHON - Pandas DataFrame - Intellisense 不显示对象的属性/方法

python - 将列值分配给数据框中的变量