【问题标题】:Deriving new data from Pandas datetime column从 Pandas 日期时间列派生新数据
【发布时间】:2014-06-13 16:22:21
【问题描述】:

我在pandas DataFrame 中有一列时间戳(以毫秒为单位)。从时间戳中,我试图在单独的列中导出时间戳的小时、分钟、星期几和月份。

我尝试在整个列中使用apply 函数,但无济于事。因此,我采用了一种非常天真的(但不是很简洁)的方法来创建这些列:

import pandas
import datetime

df=pd.DataFrame( {'time':[1401811621559, 1402673694105, 1402673749561, 1401811615479, 1402673708254], 'person':['Harry', 'Ann', 'Sue', 'Jeremy', 'Anne']})

df['time'] = pandas.to_datetime(df.time, unit='ms')
days = []
tod = []
month = []
minutes = []
for row in df['time']:
    days.append(row.strftime('%w'))
    tod.append(row.strftime('%H'))
    month.append(row.strftime('%m'))
    minutes.append(row.strftime('%M'))
##
df['dayOfWeek'] = days
df['timeOfDay'] = tod
df['month'] = month
df['minutes'] = minutes

有没有类似的方法来做到这一点?

df['dayOfWeek'] = df['time'].apply(strftime('%w'),axis = 1)

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'strftime' is not defined

【问题讨论】:

    标签: python datetime pandas


    【解决方案1】:

    目前您必须将列包装在 DatetimeIndex 中:

    In [11]: dti = pd.DatetimeIndex(df['time'])
    
    In [12]: dti.dayofweek
    Out[12]: array([1, 4, 4, 1, 4])
    
    In [13]: dti.time
    Out[13]:
    array([datetime.time(16, 7, 1, 559000), datetime.time(15, 34, 54, 105000),
           datetime.time(15, 35, 49, 561000), datetime.time(16, 6, 55, 479000),
           datetime.time(15, 35, 8, 254000)], dtype=object)
    
    In [14]: dti.month
    Out[14]: array([6, 6, 6, 6, 6])
    
    In [15]: dti.minute
    Out[15]: array([ 7, 34, 35,  6, 35])
    

    等等

    请参阅 this issue 以使这些方法直接从日期时间序列中可用。

    【讨论】:

      【解决方案2】:

      您也可以将其设为 lambda 函数:

      df['dayOfWeek2'] = df.time.apply(lambda x:x.strftime('%w'))
      

      现在输入

      df.dayOfWeek2 == df.dayOfWeek
      

      产量

      0    True
      1    True
      2    True
      3    True
      4    True
      dtype: bool
      

      【讨论】:

      • 谢谢!效果很好。
      【解决方案3】:

      是的,稍微修改一下你的代码...

      def timeGroups(row):
          row['days'] = row['time'].strftime('%w'))
          #do the same thing for month,seconds,etc.
          return row
      df['dayOfWeek'] = df['time'].apply(timeGroups,axis = 1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 1970-01-01
        • 2020-08-21
        • 2012-09-04
        • 2021-01-30
        • 2018-09-16
        • 2018-02-02
        相关资源
        最近更新 更多