Python - 遍历属性列表 [英] Python - Iterate over a list of attributes
问题描述
我的数据集中有一个特性,它是一个 Pandas 时间戳对象.它具有(除其他外)以下属性:年、小时、星期几、月.
I have a feature in my data set that is a pandas timestamp object. It has (among many others) the following attributes: year, hour, dayofweek, month.
我可以使用一些蛮力方法基于这些属性创建新特征:
I can create new features based on these attributes using some brute force methods:
df["year"] = df["timeStamp"].apply(lambda x : x.year)
df["hour"] = df["timeStamp"].apply(lambda x : x.hour)
...
但是,我想遍历一个列表:
However, I want to iterate over a list:
nomtimes = ["year", "hour", "month", "dayofweek"]
for i in nomtimes:
df[i] = df["timeStamp"].apply(lambda x : x.i)
我收到以下 AttributeError: 'Timestamp' object has no attribute 'i',我明白了为什么我会遇到这个错误.
I get the following AttributeError: 'Timestamp' object has no attribute 'i', and I get it and understand why I am having this error.
如何将引用的字符串取消引用以便我可以将其作为属性传递?
How can I get the quoted string to unquote so that I can pass it as an attribute?
推荐答案
你只需要getattr()
:
df[i] = df["timeStamp"].apply(lambda x : getattr(x, i))
这篇关于Python - 遍历属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!