Pandas .dropna()指定属性

时间:2016-08-31 05:22:32

标签: python pandas

我有这段代码从列类型中删除空值,特别是看Dog。

cd.loc[cd['Type'] == 'Dog'].dropna(subset = ['Killed'], inplace = True)

当与Type = Dog关联的['Killed']列具有NaN值时,我想知道。

上面的代码生成了这个pandas错误:

 A value is trying to be set on a copy of a slice from a DataFrame

当''Type'] =='Dog'时,还有另一种方法可以让我在['Killed']上投降吗?

(这是我的第一篇文章),对不起,如果我无法正确解释 干杯

2 个答案:

答案 0 :(得分:3)

听起来你要说的是你要删除Type为“Dog”且Killed为NaN的行。所以只需选择否定该条件:

cd = cd.loc[~((cd.Type=="Dog") & cd.Killed.isnull())]

答案 1 :(得分:3)

与@ BrenBarn的答案非常相似,但使用dropinplace

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

enter image description here

与DeMorgan法律相同

cond1 = cd.Type == 'Dog'
cond2 = cd.Killed.isnull()
cd[~cond1 | ~cond2]

一个愚蠢的人,因为我觉得这样!

cd.groupby('Type', group_keys=False) \
    .apply(lambda df: df.dropna(subset=['Killed']) if df.name == 'Dog' else df)