Github Copilot 给出的答案我觉得比较好,觉得是真正受教了,我知道自己还是固化在 Python 的列表循环里面,还没有真正走出来真正理解 Pandas 的魅力。

在 Pandas 中,你可以使用 fillna() 函数来替换 DataFrame 中的空值。如果你想将 country_list['country_name'] 的空值替换成 country_id 的值,你可以使用以下代码:

country_list['country_name'].fillna(country_list['country_id'], inplace=True)

在这个例子中,fillna(country_list['country_id']) 表示将 country_name 列中的空值替换为 country_id 列中的对应值。inplace=True 表示直接在原 DataFrame 上进行修改,而不是创建一个新的 DataFrame。

其实还好,函数名还是比较好理解的,fill_na,即填充空值么,呵呵。

而我的方案是这样的:

country_list = pd.read_excel('./countries_index.xlsx')  
  
for index, row in country_list.iterrows():  
    print(f"{row['country_id']}{Year.HEAD.value}{SPEC}.csv", row['country_id'] if pd.isnull(row['country_name']) else f"{row['country_name']}", )

这甚至也是在 Github Copilot 的提示下做出来的,如果用 row['country_name']=="" 判断的话,解决不了问题,依然是 nan

如果用 row['country_name].isNull() 则会报错:AttributeError: ‘str’ object has no attribute ‘isnull’,即字符串对象没有属性:isNull()

最终用了一个折中的办法,遍历,然后用了 pd.isnull() 函数来解决问题,但是不如 fillna 更加地直观,快捷。官方说法也是这种方法要高于单个遍历的方法。