【问题标题】:How to write a loop with a dictonary如何用字典编写循环
【发布时间】: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


【解决方案1】:

每条评论:

def contains(x, y):
    for i in x:
        if i.lower() in y.lower():
            return True
    return False

for key,val in dict.items():
    df['Test'] = df['Countrylist'].apply(lambda x: key if contains([val], x) else np.nan)

同样,由于您没有提供输入/输出对,因此很难检查它是否符合您的要求。特别是contains(['foo', 'bar'], 'FOOTBALL') == True(这可能是您想要的,但从函数名称中并不明显)。

此外,请注意此代码在循环中多次重新分配 df['Test']。该列的最终值取决于哪个循环迭代是最后一个(对于 Python 版本 see the accepted answer here,这不是您可以依赖的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2020-04-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多