[英]Pandas .dropna() on specify attribute
I have this code to drop null values from column Type, specifically looking at Dog. 我有这个代码从列类型中删除空值,特别是看看Dog。
cd.loc[cd['Type'] == 'Dog'].dropna(subset = ['Killed'], inplace = True)
I would like to dropna when the ['Killed'] column associating with Type = Dog has NaN value. 当与Type = Dog关联的['Killed']列具有NaN值时,我想知道。
The code above generate this pandas error: 上面的代码生成了这个pandas错误:
A value is trying to be set on a copy of a slice from a DataFrame
Is there another way where can I dropna on ['Killed'] when ['Type'] == 'Dog'? 当['Type'] =='Dog'时,还有另一种方法可以让我在['Killed']上投降吗?
(This is my first post), sorry if I can't explain properly Cheers (这是我的第一篇文章),对不起,如果我不能正确解释干杯
It sounds like what you are saying is you want to remove rows where Type is "Dog" and Killed is NaN
. 听起来你要说的是你要删除Type为“Dog”且Killed为NaN
。 So just select the negation of that condition: 所以只需选择对该条件的否定:
cd = cd.loc[~((cd.Type=="Dog") & cd.Killed.isnull())]
Very similar to @BrenBarn's answer but using drop
and inplace
与@ BrenBarn的答案非常相似,但使用drop
和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
Equivalently with DeMorgan's law 与DeMorgan的法律同等
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.