![](/img/trans.png)
[英]pandas Dataframe Replace NaN values with with previous value based on a key column
[英]How to replace NaN value in column in Dataframe based on values from another column in same dataframe
下面是我正在工作的 Dataframe。 我想使用“國家”和“部門”列中的值替換“分數”列中的 NaN 值
Country Sectors Score
0 USA MECH NaN
1 IND ELEC 10.0
2 USA CHEM NaN
3 RUS ENT 34.0
4 PAK MATH 45.0
5 SL LAN 23.0
6 USA CHEM 56.0
7 IND ELEC 32.0
8 USA CHEM NaN
9 RUS ENT 45.0
10 PAK MATH 45.0
下面是我嘗試過的代碼
import pandas as pd
import numpy as np
df = pd.read_csv('../Data/Data.csv')
df['Score'] = df[(df['Country'] == 'USA') & (df['Sectors'] == 'CHEM') & (df['Score'].isnull())]['Score'].fillna(10)
print(df)
```but I am getting below result```
Country Sectors Score
0 USA MECH NaN
1 IND ELEC NaN
2 USA CHEM 10.0
3 RUS ENT NaN
4 PAK MATH NaN
5 SL LAN NaN
6 USA CHEM NaN
7 IND ELEC NaN
8 USA CHEM 10.0
9 RUS ENT NaN
10 PAK MATH NaN
我只想替換特定於國家 == 'USA' 和 Sectors == 'CHEM' 的 NaN 值,並保持所有值不變。 有人可以幫忙嗎?```
您可以使用np.where
:
>>> df = pd.DataFrame({'Country':['USA', 'IND','USA'], 'Sectors':['MECH', 'ELEC','CHEM'], 'Score':[45.0, 30.0, np.NaN]})
>>> df["Score"] = np.where((df["Country"]=='USA') & (df['Sectors'] == 'CHEM'), 10, df["Score"])
>>> df
Country Sectors Score
0 USA MECH 45.0
1 IND ELEC 30.0
2 USA CHEM 10.0
如果df["Country"]=='USA'
和df['Sectors'] == 'CHEM'
,則df['Score']
設置為10
,否則df['Score']
中的原始值為放。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.