【发布时间】:2022-01-14 17:09:35
【问题描述】:
如何仅在 NaN 值中用另一个 column ["country"] 填充 column ["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 任何人都可以帮我提供有效的代码吗? 请!
【问题讨论】:
标签: python pandas database dataframe replace