指定属性上的 Pandas .dropna() [英] Pandas .dropna() on specify attribute
问题描述
我有这段代码可以从 Type 列中删除空值,特别是查看 Dog.
I have this code to drop null values from column Type, specifically looking at Dog.
cd.loc[cd['Type'] == 'Dog'].dropna(subset = ['Killed'], inplace = True)
当与 Type = Dog 关联的 ['Killed'] 列具有 NaN 值时,我想删除.
I would like to dropna when the ['Killed'] column associating with Type = Dog has NaN value.
上面的代码生成了这个熊猫错误:
The code above generate this pandas error:
A value is trying to be set on a copy of a slice from a DataFrame
当 ['Type'] == 'Dog' 时,有没有其他方法可以在 ['Killed'] 上放置?
Is there another way where can I dropna on ['Killed'] when ['Type'] == 'Dog'?
(这是我的第一篇文章),如果我不能正确解释,请见谅干杯
(This is my first post), sorry if I can't explain properly Cheers
推荐答案
与@BrenBarn 的回答非常相似,但使用了 drop
和 inplace
Very similar to @BrenBarn's answer but using drop
and inplace
cd.drop(cd[(cd.Type == 'Dog') & (cd.Killed.isnull())].index, inplace=True)
设置
cd = pd.DataFrame([
['Dog', 'Yorkie'],
['Cat', 'Rag Doll'],
['Cat', None],
['Bird', 'Caique'],
['Dog', None],
], columns=['Type', 'Killed'])
解决方案
cd.drop(cd[(cd.Type == 'Dog') & (cd.Killed.isnull())].index, inplace=True)
cd
等同于德摩根定律
cond1 = cd.Type == 'Dog'
cond2 = cd.Killed.isnull()
cd[~cond1 | ~cond2]
<小时>
一个愚蠢的,因为我喜欢它!
A silly one, because I felt like it!
cd.groupby('Type', group_keys=False) \
.apply(lambda df: df.dropna(subset=['Killed']) if df.name == 'Dog' else df)
这篇关于指定属性上的 Pandas .dropna()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!