Pandas: 使用 apply 时明显的类型不匹配

Pandas: apparent type mismatch using apply

说我想apply一个函数到user_location

df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 4139 entries, 2020-12-20 06:06:44 to 2021-01-13 04:45:10
Data columns (total 15 columns):
 #   Column            Non-Null Count  Dtype 
---  ------            --------------  ----- 
 0   id                4139 non-null   int64 
 1   user_name         4139 non-null   object
 2   user_location     3282 non-null   object
....

为什么我得到一个 TypeError'float' 类型的参数不可迭代)做

def get_country(s):
    for country in pycountry.countries:
        if country.name in s:
            return country.name

d = df["user_location"].apply(get_country)

get_country('Some text about Canada') 很有魅力

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-50fde3ed5073> in <module>
      6 countries = [country.name for country in pycountry.countries]
      7 
----> 8 d = df["user_location"].apply(get_country)
      9 
     10 df["user_location"]

~/.local/lib/python3.7/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   4106             else:
   4107                 values = self.astype(object)._values
-> 4108                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   4109 
   4110         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

<ipython-input-89-50fde3ed5073> in get_country(s)
      1 def get_country(s):
      2     for country in pycountry.countries:
----> 3         if country.name in s:
      4             return country.name
      5 

TypeError: argument of type 'float' is not iterable

如果 apply 真的应用 get_country 元素明智,为什么它抱怨 float 不可迭代?我试图设置 convert_dtype=False 以防万一,但它并没有改变任何事情。

也许 user_location 中的一些与数字混在一起了? 就逼他们"if country.name in str(s):"