Python:如何将字符串作为函数的参数传递

时间:2017-03-29 15:29:31

标签: 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
tx     Texas
ca     California
fl     Florida
wa     Washington
ny     New York
az     Arizona

2 个答案:

答案 0 :(得分:3)

us.states模块有一个可以使用的查找方法:

import us
df['state_ru'] = df.state.apply(lambda x: us.states.lookup(x).name)
df

enter image description here

答案 1 :(得分:1)

是的,你可以使用getattr这样的

来做到这一点
getattr(obj, 'foo')

这相当于执行:obj.foo,当属性名称可变时非常有用。

相关问题