如何使用熊猫计算经过的月份?我写了以下内容,但这段代码并不优雅.你能告诉我一个更好的方法吗?
import pandas as pd
df = pd.DataFrame([pd.Timestamp('20161011'),
pd.Timestamp('20161101') ], columns=['date'])
df['today'] = pd.Timestamp('20161202')
df = df.assign(
elapsed_months=(12 *
(df["today"].map(lambda x: x.year) -
df["date"].map(lambda x: x.year)) +
(df["today"].map(lambda x: x.month) -
df["date"].map(lambda x: x.month))))
# Out[34]:
# date today elapsed_months
# 0 2016-10-11 2016-12-02 2
# 1 2016-11-01 2016-12-02 1
Run Code Online (Sandbox Code Playgroud)
Psi*_*dom 25
大熊猫更新0.24.0:
由于0.24.0已将api更改为从period减法返回MonthEnd对象,因此您可以按如下方式进行一些手动计算以获得整月差异:
12 * (df.today.dt.year - df.date.dt.year) + (df.today.dt.month - df.date.dt.month)
# 0 2
# 1 1
# dtype: int64
Run Code Online (Sandbox Code Playgroud)
包裹功能:
def month_diff(a, b):
return 12 * (a.dt.year - b.dt.year) + (a.dt.month - b.dt.month)
month_diff(df.today, df.date)
# 0 2
# 1 1
# dtype: int64
Run Code Online (Sandbox Code Playgroud)
在熊猫0.24.0之前.您可以将日期舍入到Month,to_period()然后减去结果:
df['elapased_months'] = df.today.dt.to_period('M') - df.date.dt.to_period('M')
df
# date today elapased_months
#0 2016-10-11 2016-12-02 2
#1 2016-11-01 2016-12-02 1
Run Code Online (Sandbox Code Playgroud)
Paw*_*erg 14
更新pandas 1.3
如果你想要整数而不是MonthEnd对象:
df['elapsed_months'] = df.today.dt.to_period('M').view(dtype='int64') - df.date.dt.to_period('M').view(dtype='int64')
df
# Out[11]:
# date today elapsed_months
# 0 2016-10-11 2016-12-02 2
# 1 2016-11-01 2016-12-02 1
Run Code Online (Sandbox Code Playgroud)
这适用于 pandas 1.1.1:
df['elapsed_months'] = df.today.dt.to_period('M').astype(int) - df.date.dt.to_period('M').astype(int)
df
# Out[11]:
# date today elapsed_months
# 0 2016-10-11 2016-12-02 2
# 1 2016-11-01 2016-12-02 1
Run Code Online (Sandbox Code Playgroud)
你也可以尝试:
df['months'] = (df['today'] - df['date']) / np.timedelta64(1, 'M')
df
# date today months
#0 2016-10-11 2016-12-02 1.708454
#1 2016-11-01 2016-12-02 1.018501
Run Code Online (Sandbox Code Playgroud)
更简单的方式,也可以使用pandas中的to_period函数来计算。
pd.to_datetime('today').to_period('M') - pd.to_datetime('2020-01-01').to_period('M')
# [Out]:
# <7 * MonthEnds>
Run Code Online (Sandbox Code Playgroud)
如果您只想要整数值,只需使用(<above_code>).n
| 归档时间: |
|
| 查看次数: |
20436 次 |
| 最近记录: |