【问题标题】:How to fill a column conditionally to values in an other column being in a list?如何有条件地将列填充为列表中另一列中的值?
【发布时间】:2016-08-01 18:12:41
【问题描述】:

在 pandas 数据框中,如何有条件地将列的值填充为列表中另一列中的值?

这个和this SO question很像,但是当我申请时:

df['type'] = np.where(df['food'] in ['apple', 'banana', 'kiwi'], 'fruit', 'oth. food')

我遇到了一个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我想in 运算符没有被覆盖以使用向量..

【问题讨论】:

  • 你在追df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')

标签: python pandas dataframe


【解决方案1】:

我觉得你可以用isin:

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')

【讨论】:

    【解决方案2】:

    这应该可以工作

    df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
    

    【讨论】:

    • :) 我们的帖子之间只有 20 秒。不错。
    • @jezrael:谢谢。。我希望我可以将两者都添加为已接受的答案;-)
    • 是的,如果你能同时添加两个:-)
    • 我想我能在你的皮肤上做些什么——也许只支持这两种解决方案。但是你输了+2,嗯。但这取决于你,你做什么。
    • 没问题。美好的一天。
    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 2021-05-21
    • 2022-01-15
    • 2023-03-21
    • 2019-09-09
    • 1970-01-01
    • 2015-03-28
    相关资源
    最近更新 更多