【问题标题】:how can I use pandas dataframe with out of bounds datetime?如何使用日期时间越界的熊猫数据框?
【发布时间】:2020-12-10 20:03:44
【问题描述】:

我有一个这样的数据框:

housing_deals.head()
Out[2]: 
         price   sale_date 
0  477,000,000  1396/10/30 
1  608,700,000  1396/11/25 
2  580,000,000  1396/10/03 
3  350,000,000  1396/12/05 
4  328,000,000  1396/03/18 

如何将 sale_date 列转换为 pandas 日期时间
我在下面看到
How to work around Python Pandas DataFrame's "Out of bounds nanosecond timestamp" error?
但我不能为我的数据框做到这一点

【问题讨论】:

    标签: python pandas python-datetime


    【解决方案1】:

    您可以将值转换为每日周期,请查看docs

    df['sale_date'] = df['sale_date'].apply(lambda x: pd.Period(x, freq='D'))
    print (df)
             price   sale_date
    0  477,000,000  1396-10-30
    1  608,700,000  1396-11-25
    2  580,000,000  1396-10-03
    3  350,000,000  1396-12-05
    4  328,000,000  1396-03-18
    

    编辑:您可以将值转换为数字,然后使用 docs 的函数:

    print (df['sale_date'].str.replace('/','').astype(int))
    0    13961030
    1    13961125
    2    13961003
    3    13961205
    4    13960318
    Name: sale_date, dtype: int32
    
    
    def conv(x):
        return pd.Period(year=x // 10000,
                         month=x // 100 % 100,
                         day=x % 100, freq='D')
      
    
    df['sale_date'] = df['sale_date'].str.replace('/','').astype(int).apply(conv)
    print (df)
    
             price   sale_date
    0  477,000,000  1396-10-30
    1  608,700,000  1396-11-25
    2  580,000,000  1396-10-03
    3  350,000,000  1396-12-05
    4  328,000,000  1396-03-18
    

    【讨论】:

    • 它给了我这个错误:day is out of range for month 因为我的数据框中的日期为 31,我该如何处理?@jezrael
    • @saeedzali - 你的熊猫版本是什么?
    • 它是'1.0.5' @jezrael
    • @saeedzali - 问题出在数据 housing_deals.head() 上?全部包含所有数据?这意味着工作df['sale_date'].head().apply(lambda x: pd.Period(x, freq='D')) 而不是df['sale_date'].apply(lambda x: pd.Period(x, freq='D'))
    • @saeedzali - 好的,如果升级到最新版本,我希望有所帮助。
    猜你喜欢
    • 2021-05-03
    • 2023-03-20
    • 2020-07-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2018-06-16
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多