Python-遍历属性列表 [英] Python - Iterate over a list of attributes
本文介绍了Python-遍历属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据集中有一个功能是熊猫时间戳对象.它(除其他外)具有以下属性:年,小时,星期几,月.
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'对象没有属性'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屋!
查看全文