如何检查一行的数据是不是在列表中,在 np.where() 内部?

Posted

技术标签:

【中文标题】如何检查一行的数据是不是在列表中,在 np.where() 内部?【英文标题】:How to check whether data of a row is in list, inside of np.where()?如何检查一行的数据是否在列表中,在 np.where() 内部? 【发布时间】:2018-07-15 06:14:16 【问题描述】:
developed_countries = ["NOR","AUS","CHE","DEU","DNK","SGP","NLD","IRL","ISL","CAN","USA","NZL","SWE","LIE","GBR"]

recent_indicators['Developed'] = np.where(recent_indicators['CountryCode'] in developed_countries, 1, 0)

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

recent_indicators 是 pandas DataFrame。检查开发的国家中是否提到了“国家代码”的替代方法是什么?

【问题讨论】:

期望的输出是什么?请展示您的 df 输入和输出示例 【参考方案1】:

你可以在pandas过滤中直接使用.isin()——

recent_indicators_filtered = recent_indicators[recent_indicators['CountryCode'].isin(developed_countries)]

此外,如果已开发,您可以提出一个布尔列,上面写着 True -

recent_indicators['Developed'] = recent_indicators['CountryCode'].isin(developed_countries)

【讨论】:

以上是关于如何检查一行的数据是不是在列表中,在 np.where() 内部?的主要内容,如果未能解决你的问题,请参考以下文章