Python - 迭代属性列表

The*_*xah 3 python lambda datetime apply pandas

我的数据集中有一个特性,它是一个 Pandas 时间戳对象。它具有(除其他外)以下属性:年、小时、星期几、月。

我可以使用一些蛮力方法基于这些属性创建新功能:

df["year"] = df["timeStamp"].apply(lambda x : x.year)

df["hour"] = df["timeStamp"].apply(lambda x : x.hour)
Run Code Online (Sandbox Code Playgroud)

. . .

但是,我想遍历一个列表:

nomtimes = ["year", "hour", "month", "dayofweek"]


for i in nomtimes:

  df[i] = df["timeStamp"].apply(lambda x : x.i)
Run Code Online (Sandbox Code Playgroud)

我得到以下 AttributeError: 'Timestamp' object has no attribute 'i',我明白了为什么我会遇到这个错误。

如何让引用的字符串取消引用,以便我可以将其作为属性传递?

jua*_*aga 5

不要.apply在这里使用,pandas 有各种用于处理日期时间对象的内置实用程序,请使用dt系列对象上的属性:

In [11]: start = datetime(2011, 1, 1)
    ...: end = datetime(2012, 1, 1)
    ...:

In [12]: df = pd.DataFrame({'data':pd.date_range(start, end)})

In [13]: df.dtypes
Out[13]:
data    datetime64[ns]
dtype: object

In [14]: df['year'] = df.data.dt.year

In [15]: df['hour'] = df.data.dt.hour

In [16]: df['month'] = df.data.dt.month

In [17]: df['dayofweek'] = df.data.dt.dayofweek

In [18]: df.head()
Out[18]:
        data  year  hour  month  dayofweek
0 2011-01-01  2011     0      1          5
1 2011-01-02  2011     0      1          6
2 2011-01-03  2011     0      1          0
3 2011-01-04  2011     0      1          1
4 2011-01-05  2011     0      1          2
Run Code Online (Sandbox Code Playgroud)

或者,根据需要动态使用getattr

In [24]: df = pd.DataFrame({'data':pd.date_range(start, end)})

In [25]: nomtimes = ["year", "hour", "month", "dayofweek"]
    ...:

In [26]: df.head()
Out[26]:
        data
0 2011-01-01
1 2011-01-02
2 2011-01-03
3 2011-01-04
4 2011-01-05

In [27]: for t in nomtimes:
    ...:     df[t] = getattr(df.data.dt, t)
    ...:

In [28]: df.head()
Out[28]:
        data  year  hour  month  dayofweek
0 2011-01-01  2011     0      1          5
1 2011-01-02  2011     0      1          6
2 2011-01-03  2011     0      1          0
3 2011-01-04  2011     0      1          1
4 2011-01-05  2011     0      1          2
Run Code Online (Sandbox Code Playgroud)

如果您必须使用单线,请使用:

In [30]: df = pd.DataFrame({'data':pd.date_range(start, end)})

In [31]: df.head()
Out[31]:
        data
0 2011-01-01
1 2011-01-02
2 2011-01-03
3 2011-01-04
4 2011-01-05

In [32]: df = df.assign(**{t:getattr(df.data.dt,t) for t in nomtimes})

In [33]: df.head()
Out[33]:
        data  dayofweek  hour  month  year
0 2011-01-01          5     0      1  2011
1 2011-01-02          6     0      1  2011
2 2011-01-03          0     0      1  2011
3 2011-01-04          1     0      1  2011
4 2011-01-05          2     0      1  2011
Run Code Online (Sandbox Code Playgroud)