有没有更好的方法来使用方法 'ffill' 和 pandas 进行分段填充?

is there a better way to do segmented fillna with method 'ffill' with pandas?

让我解释一下这种情况。问题是我目前正在处理有时分类有时不分类的数据。所以我决定使用 fillna 的 pandas 和 'ffil' 作为方法。我只是觉得这不是最佳的 and/or 清洁解决方案。如果有人能用更好的方法帮助我,我将不胜感激。这里有一些代码来证明这一点:

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)

Returns

    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)

returns正是我想要的

    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

困境如下。如果我有成千上万个样本的这种情况会发生什么。有没有更好的办法?请帮忙

我们可以做到

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