我想在 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:系列的真值不明确。使用a.empty,
a.bool()、a.item()、a.any() 或 a.all()。
我不知道问题是什么以及如何解决。我缺少什么?
Use isin http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html检查会员资格:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)