我可以复制其他行和列中的值并自动替换缺失的值吗



所以,我的数据帧是

price   model_year  model           condition   cylinders   fuel    odometer    transmission    type    paint_color is_4wd  date_posted days_listed
0   9400    2011.0      bmw x5          good        6.0         gas     145000.0    automatic       SUV     NaN         True    2018-06-23  19
1   25500   NaN         ford f-150      good        6.0         gas     88705.0     automatic       pickup  white       True    2018-10-19  50
2   5500    2013.0      hyundai sonata  like new    4.0         gas     110000.0    automatic       sedan   red         False   2019-02-07  79
3   1500    2003.0      ford f-150      fair        8.0         gas     NaN         automatic       pickup  NaN         False   2019-03-22  9
4   14900   2017.0      chrysler 200    excellent   4.0         gas     80903.0     automatic       sedan   black       False   2019-04-02  28

如您所见,第1行的型号与第3行的型号相同,但第1行缺少型号年份。很自然,我可以用第3行替换第1行的车型年份,这样就没有NaN了,我知道我可以手动更改它,但数据帧超过50000行长,还有更多类似的值。有没有一种自动的方法可以这样替换这些值?

编辑:在查看了刚才的df之后,我意识到我不能真的像那样更换车型年份,因为即使在同一车型内,它也可能发生变化,尽管我仍然很想知道它是如何做到的,如果可能的话,以供未来参考

您可以将数据帧与其自身合并并填充它。

df_want = df.merge(df[['model_year','model']].dropna().drop_duplicates(),on='model',how='left')
df_want['model_year'] = df_want['model_year_x'].fillna(df_want['model_year_y']
df_want = df_want.drop(['model_year_x','model_year_y'],axis=1)

是的,您可以将所有NaN模型年份替换为非NaN条目,如下所示:

models = df['model'].unique()
for m in models:
year = df.loc[(df['model_year'].notna()) & (df['model'] == m)]['model_year'].values[0]
df.at[(df['model_year'].isna()) & (df['model'] == m), 'model_year'] = year

最新更新