有没有更好的方法用“菲尔”法对Pandas进行分段填充?

2024-09-29 01:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

让我解释一下这种情况。问题是我目前正在处理的数据有时是分类的,有时不是。所以我决定用带有“ffil”的菲尔娜熊猫作为方法。我只是觉得这不是最佳和/或更清洁的解决方案。如果有人能帮我找到更好的办法,我将不胜感激。这里有一些代码来说明这一点:

data = {
    "detail":['apple mac', 'apple iphone x', 'samsumg galaxy s10', 'samsumg galaxy s10', 'hp computer'],
    'category': ['computer', 'phone', 'phone', np.NaN, np.NaN]
}

df = pd.DataFrame(data)

返回

    detail              category
0   apple mac           computer
1   apple iphone x      phone
2   samsumg galaxy s10  phone
3   samsumg galaxy s10  NaN
4   hp computer         NaN

首先,我过滤了没有类别的细节值:

details_without_cats = df[df.category.isnull()].detail.unique()

然后我循环这些值以填充对应项:

for detail_wc in details_without_cats:
    df[df.detail == detail_wc] = df[df.detail == detail_wc].fillna(method = 'ffill')
print(df)

返回的正是我想要的

    detail              category
0   apple mac           computer
1   apple iphone x      phone
2   samsumg galaxy s10  phone
3   samsumg galaxy s10  phone
4   hp computer         NaN

困境如下。如果我有数千或数百万样本的情况会发生什么。有更好的办法吗?请帮忙


Tags: appledfmac情况phonenangalaxycomputer
2条回答

我们能做到

df['category']=df.groupby('detail')['category'].ffill()
df
               detail  category
0           apple mac  computer
1      apple iphone x     phone
2  samsumg galaxy s10     phone
3  samsumg galaxy s10     phone
4         hp computer       NaN

如果要创建具有值的项目目录以供以后使用,可以执行以下操作:

maps = df.dropna().set_index('detail').to_dict()['category']
df['category'] = df.set_index('detail').index.map(maps)

地图

{'apple mac': 'computer',
 'apple iphone x': 'phone',
 'samsumg galaxy s10': 'phone'}

输出:

               detail  category
0           apple mac  computer
1      apple iphone x     phone
2  samsumg galaxy s10     phone
3  samsumg galaxy s10     phone
4         hp computer       NaN

相关问题 更多 >