根据另一个系列的条件,使用字典替换系列对象中的项目

Using dictionary to replace items in Series object, based on condition from another Series

我有一个包含一系列国家和一系列国家的数据框。 Country 系列有多个缺失值。我有一本美国各州的字典,用来清理美国系列。我想用它来表示,如果字典中有 State,那么 Country 应该是 USA。

我可以使用映射到美国的州字典,即{'AL': 'USA', 'AK': 'USA' ...} 然后使用 df['Country']= df['Country'].map(dict) 但我确定有 better/smarter/simpler 方法可以做到这一点。

我试过这个:

test = df[['State', 'Country']]
for a, b in test.itertuples(index=False):
    if a in us_state_abbrev.values():
        b = "USA"
    elif a in ca_province_abbrev.values():
        b = "Canada"

其中 test.head() returns:

         State       Country
0          MO           NaN
1          IA           USA
2          MI           NaN
3          AB        Canada
4          ON        Canada

us_state_abbrev = {'Alabama': 'AL', 'Alaska': 'AK' ...}

但没有任何变化,尽管 if-else 语句有效。这是为什么?

我也试过:

test['Country'] = np.where(test['State'] in us_state_abbrev.values(), "USA", test['Country'])

但我收到一个 ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。这是为什么?

不要使用 in。您需要 isinnp.where

us_state_abbrev = {'Alabama': 'AL', 'Alaska': 'AK', 'IOWA': 'IA', 'Mississippi': 'MI', 'Missouri': 'MO'}

test['Country'] = np.where(test['State'].isin(us_state_abbrev.values()), "USA", test['Country'])

Out[143]:
  State Country
0    MO     USA
1    IA     USA
2    MI     USA
3    AB  Canada
4    ON  Canada