如何僅在 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 分鐘并且每次都崩潰。因為它一次替換一個值。 像這樣 任何人都可以幫助我為此提供有效的代碼嗎?請!
uj5u.com熱心網友回復:
也許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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412268.html
標籤:
上一篇:如何填充已填充關系的關系?
下一篇:通過示例提高查詢性能
