【问题标题】:Pandas : converting a period from an 'object' type to a 'period' type, to be able to make calculationsPandas:将句点从“对象”类型转换为“句点”类型,以便能够进行计算
【发布时间】:2020-07-29 11:00:26
【问题描述】:

我刚刚从 NOAA (url: 'https://www.ncdc.noaa.gov/cag/time-series/global/globe/land_ocean/p12/12/1880-2020.csv') 下载了一个基本文件,并且有这个 'Period' 目前是一个 'object' 类型,显示 stg 像一个 YYYYMM 值:

import pandas as pd
test=pd.read_csv('https://www.ncdc.noaa.gov/cag/time-series/global/globe/land_ocean/p12/12/1880-2020.csv', parse_dates=['Year'], infer_datetime_format=True, skiprows=4)
test.columns=['Period','Discr']
test.head()

Period  Discr
0   188001  -0.06
1   188002  -0.14
2   188003  -0.09
3   188004  -0.05
4   188005  -0.09

test.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1683 entries, 0 to 1682

数据列(共2列):

 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Period  1683 non-null   object 
 1   Discr   1683 non-null   float64
dtypes: float64(1), object(1)
memory usage: 26.4+ KB

我尝试使用dt.to_period(freq='M'), pd.PeriodIndex ...,但无法解决我的问题...

因此我需要帮助。提前致谢

【问题讨论】:

  • 使用dt['Year'].dt.to_period(freq='m')
  • 为此感谢@jezrael,但我不知道如何使用它:'dt' 意味着我首先必须导入 datetime 模块,我猜是这样做的。但是,如果我输入 test['Period'] = test['Period'].dt.to_Period(freq='M'),(因为 test 是数据框名称,Period 是列名称),我仍然有一个错误 AttributeError: Can only use .dt accessor with datetimelike values... :-/
  • 所以先用df['Period'] = pd.to_datetime(df['Period'])
  • 我一开始是这样做的,最终效果很好,直到默认日历似乎从 1970 - 01 - 01 :-/ 开始,而我的数据从 1880 - 01 - 01 开始。这里我也想出了解决这个问题的方法。这是您宝贵的帮助!!
  • 好的,我明白了。已添加答案。

标签: python pandas


【解决方案1】:

使用自定义函数,从docs编辑函数:

df['Period']=df['Period'].apply(lambda x: pd.Period(year=x // 100, month=x % 100, freq='M'))
print (df)
    Period  Discr
0  1880-01  -0.06
1  1880-02  -0.14
2  1880-03  -0.09
3  1880-04  -0.05
4  1880-05  -0.09

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2012-09-23
    • 2018-02-15
    • 2018-06-25
    相关资源
    最近更新 更多