pandas 面試題挑戰十一
阿新 • • 發佈:2020-12-04
把DataFrame中'Min.Price', 'Max.Price'缺失的值用該列的均值填充
現有資料如下:
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
資料如下:
把'Min.Price', 'Max.Price'缺失的值用該列的均值填充
解決方法如下:
df_out = df[['Min.Price', 'Max.Price']] = df[['Min.Price', 'Max.Price']].apply(lambda x: x.fillna(x.mean())) df_out
把DataFrame中'Min.Price', 'Max.Price'缺失的值用該列的均值, 中位數填充
現有資料如下:
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
資料如下:
把'Min.Price', 'Max.Price'缺失的值用該列的均值,中位數填充
解決方法如下
d = {'Min.Price': np.nanmean, 'Max.Price': np.nanmedian} df[['Min.Price', 'Max.Price']] = df[['Min.Price', 'Max.Price']].apply(lambda x, d : x.fillna(d[x.name](x)), args=(d, )) df
重點解讀: df[['Min.Price', 'Max.Price']].apply(lambda x, d : x.fillna(d[x.name]), args=(d, ))appley中,可以通過args引數傳遞全域性變數,本例中傳遞的是d,注意傳遞是元組,所以別忘了後面的“,”。