[英]How to replace values in column when other column is not nan or replace with other?
[英]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
我應該做什么代碼來填充 state 列,僅在 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 分鍾並且每次都崩潰。 因為它一次替換一個值。 像這樣任何人都可以幫助我為此提供有效的代碼嗎? 請!
也許在不檢查 isnull() 和 replace() 的情況下使用fillna
:
df['state'].fillna(df['country'], inplace=True)
print(df)
Output
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.