【问题标题】:Modify Pandas dataframe to list year month and date修改 Pandas 数据框以列出年份月份和日期
【发布时间】:2015-03-24 16:27:26
【问题描述】:

我想修改我在下面创建的数据框:

from datetime import date
from dateutil.rrule import rrule, DAILY, YEARLY
from dateutil.relativedelta import *
import pandas

START_YR = 2010
END_YR = 2013

strt_date = datetime.date(START_YR, 1, 1)
end_date  = datetime.date(END_YR, 12, 31)

dt = rrule(DAILY, dtstart=strt_date, until=end_date)

serie_1 = pandas.Series(np.random.randn(dt.count()), \
        index = pandas.date_range(strt_date, end_date))

如何创建一个数据框,将年月日作为单独的列?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    仅访问datetime 属性会明显更快:

    df['date'] = df.index.date
    df['year'] = df.index.year
    df['month'] = df.index.month
    

    用列表推导法比较时间:

    In [25]:
    
    %%timeit
    df['month'] = [ts.to_period('M') for ts in df.index]
    df['year'] = [ts.to_period('Y') for ts in df.index]
    df['month_int'] = [ts.month for ts in df.index]
    1 loops, best of 3: 664 ms per loop
    In [26]:
    
    %%timeit
    df['date'] = df.index.date
    df['year'] = df.index.year
    df['month'] = df.index.month
    
    100 loops, best of 3: 5.96 ms per loop
    

    因此使用 datetime 属性的速度提高了 100 倍以上

    【讨论】:

    • 是的,属性的执行速度更快,但 Periods 在 Pandas 生态系统中的表现更好(例如绘图、groupby 等)。期间存储为对象(因此占用更多内存)并且不容易保存到数据库中。两种方法之间的使用将取决于偏好和数据量。
    【解决方案2】:

    将系列转换为 DataFrame,然后将新列添加为 Pandas 句点。 如果您只想将月份设为整数,请参见“month_int”示例。

    df = pd.DataFrame(serie_1)
    df['month'] = [ts.to_period('M') for ts in df.index]
    df['year'] = [ts.to_period('Y') for ts in df.index]
    df['month_int'] = [ts.month for ts in df.index]
    
    >>> df
    Out[16]: 
                       0   month   year  month_int
    
    2010-01-01  0.332370  2010-01  2010          1
    2010-01-02 -0.036814  2010-01  2010          1
    2010-01-03  1.751511  2010-01  2010          1
    ...              ...      ...   ...        ...
    2013-12-29  0.345707  2013-12  2013         12
    2013-12-30 -0.395924  2013-12  2013         12
    2013-12-31 -0.614565  2013-12  2013         12
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2018-10-15
      • 1970-01-01
      相关资源
      最近更新 更多