【发布时间】:2019-11-06 00:15:06
【问题描述】:
我用键和值创建了一个字典,想在循环中写一个循环:
for key,val in dict.items():
def contains(x, y):
result = np.nan
for i in x:
if i.lower() in y.lower():
result = key
return result
df['Test'] = df['Countrylist'].apply(lambda x: contains([val], x))
所以我想检查字典中的值是否在国家列表中,如果是,则给新列测试字典中键的值。
但我的代码不起作用...
预期输出:
Countrylist Bla1 Bla2 Test
Germany 12 12 "Here should be the Key of the Dic"
【问题讨论】:
-
您可以添加一些具有预期输出的示例数据吗?
-
你的最后一行在函数“contains”中...这是你想要的吗?
-
您的最后一行代码 (
df['Test'] =...) 在函数体中return语句下方,因此它永远不会运行。将函数移出循环并仅运行循环中的最后一行可能会修复它(尽管没有输入/输出很难保证)。 -
我用预期的输出编辑了我的问题
-
@Leporello 你能告诉我我的代码应该是什么样子吗?
标签: python pandas loops dataframe dictionary