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.
Below is the shortened version of the code:
JavaScript
x
9
1
import pandas as pd
2
import numpy as np
3
4
EU = ["Austria","Belgium","Germany"]
5
6
df1 = pd.DataFrame(data={"Country":["USA","Germany","Russia","Poland"], "Capital":["Washington","Berlin","Moscow","Warsaw"]})
7
8
df1["EU"] = np.where(df1["Country"] in EU, "EU", "Other")
9
The error I get is:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I don’t know what the problem is and how to solve it. What am I missing?
Advertisement
Answer
Use isin
for check membership:
JavaScript
1
8
1
df1["EU"] = np.where(df1["Country"].isin(EU), "EU", "Other")
2
print (df1)
3
Capital Country EU
4
0 Washington USA Other
5
1 Berlin Germany EU
6
2 Moscow Russia Other
7
3 Warsaw Poland EU
8