如何仅在 NaN 值中将一列的值替换为其他列?

How to replace the values of a column to other columns only in NaN values?

如何仅在 NaN 值中用另一个 列 ["country"] 填充 列 ["state"] 的值?

就像这个Pandas DataFrame:

         state   country  sum
0          NaN     China    1
1        Assam     India    2
2        Odisa     India    3
3        Bihar     India    4
4          NaN     India    5
5          NaN  Srilanka    6
6          NaN   Malaysia   7
7          NaN    Bhutan    8
8   California        US    9
9        Texas        US   10
10     Newyork        US   11
11         NaN        US   12
12         NaN    Canada   13

我应该用什么代码来用 NaN 值的国家列填充状态列,如下所示:

         state   country  sum
0        China     China    1
1        Assam     India    2
2        Odisa     India    3
3        Bihar     India    4
4        India     India    5
5     Srilanka  Srilanka    6
6     Malaysia  Malaysia    7
7       Bhutan    Bhutan    8
8   California        US    9
9        Texas        US   10
10     Newyork        US   11
11          US        US   12
12      Canada    Canada   13

我可以使用这个代码:

df.loc[df['state'].isnull(), 'state'] = df[df['state'].isnull()]['country'].replace(df['country'])

但是在一个有 300K 行的非常大的数据集中,它计算了 5-6 分钟并且每次都崩溃了。因为它一次替换一个值。 Like this 任何人都可以帮助我为此提供有效的代码吗? 请!

可能使用 fillna 而不检查 isnull() 和 replace():

df['state'].fillna(df['country'], inplace=True)
print(df)

输出

         state   country  sum
0        China     China    1
1        Assam     India    2
2        Odisa     India    3
3        Bihar     India    4
4        India     India    5
5     Srilanka  Srilanka    6
6     Malaysia  Malaysia    7
7       Bhutan    Bhutan    8
8   California        US    9
9        Texas        US   10
10     Newyork        US   11
11          US        US   12
12      Canada    Canada   13