让我解释一下这种情况。问题是我目前正在处理的数据有时是分类的,有时不是。所以我决定用带有“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
困境如下。如果我有数千或数百万样本的情况会发生什么。有更好的办法吗?请帮忙
我们能做到
如果要创建具有值的项目目录以供以后使用,可以执行以下操作:
地图
输出:
相关问题 更多 >
编程相关推荐