我有一個 df(car_data),其中有 2 列:model 和 is_4wd。
is_4wd 為 0 或 1,并且有大約 25,000 個缺失值。但是,我知道有些型號是 4wd,因為它們已經有 1,而相同的型號有 nan。
如何替換我知道它們已經為 1 的模型的 nan 值?
我創建了一個 for 回圈,但我必須將所有 nan 值更改為 0,創建一個獨特汽車模型的變數,并且回圈需要很長時間才能完成。
car_data['is_4wd']=car_data['is_4wd'].fillna(0)
car_4wd=car_data.query('is_4wd==1')
caru=car_4wd['model'].unique()
for index, row in car_data.iterrows():
if row['is_4wd']==0:
if row['model'] in caru:
car_data.loc[car_data.model==row['model'],'is_4wd']=1
有更好的方法嗎?嘗試了幾種 replace() 方法,但無濟于事。
df 頭看起來像這樣:(例如,您可以看到福特 f-150 在 is_4wd 中同時具有 1 和 nan)預期結果是替換所有模型的 nan,因為我知道它們已經輸入了 1 的值。
price model_year model condition cylinders fuel odometer \
0 9400 2011.0 bmw x5 good 6.0 gas 145000.0
1 25500 NaN ford f-150 good 6.0 gas 88705.0
2 5500 2013.0 hyundai sonata like new 4.0 gas 110000.0
3 1500 2003.0 ford f-150 fair 8.0 gas NaN
4 14900 2017.0 chrysler 200 excellent 4.0 gas 80903.0
transmission type paint_color is_4wd date_posted days_listed
0 automatic SUV NaN 1.0 2018-06-23 19
1 automatic pickup white 1.0 2018-10-19 50
2 automatic sedan red NaN 2019-02-07 79
3 automatic pickup NaN NaN 2019-03-22 9
4 automatic sedan black NaN 2019-04-02 28
uj5u.com熱心網友回復:
按列對資料進行分組,并按組的最大值model填充列:is_4wd
df['is_4wd'] = df.groupby('model')['is_4wd'] \
.transform(lambda x: x.fillna(x.max())).fillna(0).astype(int)
print(df[['model', 'is_4wd']])
# Output:
model is_4wd
0 bmw x5 1
1 ford f-150 1
2 hyundai sonata 0
3 ford f-150 1
4 chrysler 200 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414821.html
標籤:
上一篇:在.sort_index(level=1,axis=1)之后對資料透視表中的列進行排序
下一篇:使用pandas資料框值進行迭代
