Pandas.dropna () to specify an attribute

I have this code to drop null values ​​from a Type column, especially looking at Dog.

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

I would like to dropna when the ['Killed'] column associated with Type = Dog is NaN.

The above code generates this pandas error:

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

Is there any other way where I can reset to ['Killed'] when ['Type'] == 'Dog'?

(This is my first post) sorry if I cannot explain Greetings correctly

+4
source share
2 answers

Very similar to @BrenBarn, but using dropandinplace

cd.drop(cd[(cd.Type == 'Dog') & (cd.Killed.isnull())].index, inplace=True)

Customization

cd = pd.DataFrame([
        ['Dog', 'Yorkie'],
        ['Cat', 'Rag Doll'],
        ['Cat', None],
        ['Bird', 'Caique'],
        ['Dog', None],
    ], columns=['Type', 'Killed'])

Decision

cd.drop(cd[(cd.Type == 'Dog') & (cd.Killed.isnull())].index, inplace=True)

cd

enter image description here


Equivalent to DeMorgan's Law

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

Stupid, because I liked it!

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

, , , Type "Dog", Killed - NaN. :

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

Source: https://habr.com/ru/post/1653085/


All Articles