【问题标题】:Python Pandas Period Date difference is in * MonthEnds>, how to convert it into INT valuePython Pandas Period Date 差异在 * MonthEnds>,如何将其转换为 INT 值
【发布时间】:2020-05-29 14:43:03
【问题描述】:

我正在尝试查找期间日期差异。 Per Pandas 0.24+:从另一个期间减去一个期间将给出一个 DateOffset。而不是整数(GH21314)。但是如何获得INT结果。我已经研究过类似的查询:Why can't I subtract one date period from the next and convert to an integer? 它说添加“.n”会产生结果,但这对我不起作用。

我还尝试使用 .astype(int) 将两者都转换为 INT,但出现错误:'Period' 对象没有属性 'astype'。我一定错过了什么,不知道是什么!

我正在使用 Pandas 版本:'1.0.1'。

DDL 生成 Dataframe:

import pandas as pd

date_start = pd.Period('10/2018',freq='M')

df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
                  'date_end': ['2017-01', '2018-08', '2019-04','2018-06', 
                               '2018-12', '2018-10']})
df['date_end'] = pd.PeriodIndex(pd.to_datetime(df['date_end'], format='%Y-%m'),
                                freq='M')

df['diff'] = date_start - df['date_end']

谢谢!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您需要访问单个 Period[M] 对象,而不是系列:

    df['diff'].n
    AttributeError: 'Series' object has no attribute 'n'
    
    df['diff'].apply(lambda x: x.n)
    
    0    21
    1     2
    2    -6
    3     4
    4    -2
    5     0
    

    【讨论】:

    • 如果 date_end 中的任何一个缺少值,则上述解决方案不起作用。出现错误:AttributeError:“NatType”对象没有属性“n”。
    猜你喜欢
    • 2020-08-24
    • 2020-07-18
    • 2020-07-08
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 2015-11-02
    相关资源
    最近更新 更多