Muh*_*ris 2 python dataframe pandas
我有一个数据框如下:
model year price
Honda 2016 5.0
Yamaha 2017 5.5
Honda 2018 5.7
Yamaha 2017 NaN
Bajaj 2015 6.5
Bajaj 2015 NaN
Honda 2019 7.0
Honda 2017 NaN
Run Code Online (Sandbox Code Playgroud)
我想做的就是根据型号和年份列填写价格列中的 NaN。例如,Yamaha 2017 在第 2 行中为 5.5,在第 4 行中为 NaN。NaN 应替换为 5.5。
这只是一个示例数据集,我有 1000 多行。下一步是根据最近的年份填写模型的值,仅在模型和年份组合不存在于数据集中的情况下(我不确定我的数据集中是否有任何此类情况,因此这目前不是优先事项)。
任何正确方向的帮助都值得赞赏。谢谢。
pd.DataFrame.merge.asof如果数据集中不存在模型、年份组合,我们可以按照亲爱的mozway的建议来使用,他始终是灵感的来源,如下所示:
df['price'] = df.groupby(['model', 'year'], group_keys=False)['price'].apply(lambda x: x.ffill().bfill())
# First we sort the original data set by year values
df.sort_values('year', inplace=True)
# Then we merge the original data set with a subset of the original
# which contains no NaN values. Just note that I specified a tuple of
# values in suffixes argument to distinguish between the columns whose
# names are overlapped
df = (pd.merge_asof(df, df.loc[~ df.price.isnull()], on='year', direction='nearest', suffixes=('_x', ''))
.loc[:, ['model_x', 'year', 'price']])
df.columns = df.columns.str.rstrip('_x')
model year price
0 Bajaj 2015 6.5
1 Bajaj 2015 6.5
2 Honda 2016 5.0
3 Yamaha 2017 5.5
4 Yamaha 2017 5.5
5 Honda 2018 5.7
6 Yamaha 2018 5.7
7 Honda 2019 7.0
8 Honda 2020 7.0
Run Code Online (Sandbox Code Playgroud)
我为此案例创建了以下示例数据:
testdata = ''' model year price
Honda 2016 5.0
Yamaha 2017 5.5
Honda 2018 5.7
Yamaha 2017 NaN
Yamaha 2018 NaN
Bajaj 2015 6.5
Bajaj 2015 NaN
Honda 2019 7.0
Honda 2020 NaN
'''
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |