【问题标题】:Python pandas - new column's value if the item is in the listPython pandas - 如果项目在列表中,则为新列的值
【发布时间】:2017-12-24 08:53:28
【问题描述】:

我想在 pandas 数据框中创建一个新列。第一列包含国家名称。该列表包含我感兴趣的国家(例如欧盟)。新列应指示数据框中的国家/地区是否在列表中。

以下是代码的缩短版:

import pandas as pd
import numpy as np

EU = ["Austria","Belgium","Germany"]

df1 = pd.DataFrame(data={"Country":["USA","Germany","Russia","Poland"], "Capital":["Washington","Berlin","Moscow","Warsaw"]})

df1["EU"] = np.where(df1["Country"] in EU, "EU", "Other")

我得到的错误是:

ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

我不知道问题是什么以及如何解决它。我错过了什么?

【问题讨论】:

    标签: python pandas numpy conditional-statements


    【解决方案1】:

    使用isin 检查会员资格:

    df1["EU"] = np.where(df1["Country"].isin(EU), "EU", "Other")
    print (df1)
          Capital  Country     EU
    0  Washington      USA  Other
    1      Berlin  Germany     EU
    2      Moscow   Russia  Other
    3      Warsaw   Poland     EU
    

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 2021-03-27
      • 2021-02-15
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2014-12-24
      • 1970-01-01
      相关资源
      最近更新 更多