Python pandas - 如果项目在列表中,则新列的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45184549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:02:15  来源:igfitidea点击:

Python pandas - new column's value if the item is in the list

pythonpandasnumpyconditional

提问by Roberto

I want to create a new column in pandas dataframe. The first column contains names of countries. The list contains countries I am interested in (eg. in EU). The new colum should indicate if country from dataframe is in the list or not.

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

Below is the shortened version of the code:

以下是代码的缩短版本:

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")

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

我得到的错误是: ValueError: 系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

I don't know what the problem is and how to solve it. What am I missing? I am using Anaconda on Windows.

我不知道问题是什么以及如何解决。我错过了什么?我在 Windows 上使用 Anaconda。

Thanks

谢谢

回答by jezrael

Use isinfor check membership:

使用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