Python:如何将字符串作为函数传递';s论点
我有一个带有美国各州缩写的数据框:Python:如何将字符串作为函数传递';s论点,python,pandas,Python,Pandas,我有一个带有美国各州缩写的数据框: state tx ca fl wa ny az 我试图通过us.states模块获取全名 df['state_ru'] = df.state.apply(lambda x: us.states.x.upper().name) 它回来了 AttributeError: module 'us.states' has no attribute 'x' 我不清楚如何将x传递到us.states模块,以生成我想要的内容 预期成果: state state_ru
state
tx
ca
fl
wa
ny
az
我试图通过us.states
模块获取全名
df['state_ru'] = df.state.apply(lambda x: us.states.x.upper().name)
它回来了
AttributeError: module 'us.states' has no attribute 'x'
我不清楚如何将x
传递到us.states
模块,以生成我想要的内容
预期成果:
state state_ru
tx Texas
ca California
fl Florida
wa Washington
ny New York
az Arizona
是的,你可以这样用
getattr(obj, 'foo')
这相当于执行以下操作:
obj.foo
,当属性名称可变时非常有用。美国.states模块有一种查找方法,您可以使用:
import us
df['state_ru'] = df.state.apply(lambda x: us.states.lookup(x).name)
df