TylerNG
TylerNG

Reputation: 941

pandas drop values in a columns based other columns

Is there a way to drop a single entry in a df?

df1:
ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 4   15  6   25
113 6   7   4   10
114 3   8   2   1
115 7   1   8   10

I want to drop any Value1 if Count1 < 5 and drop any Value2 if Count2 < 5. The result would be like this:

ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 NA  NA  6   25
113 6   7   4   NA
114 NA  NA  NA  NA
115 7   1   8   10

Thanks!

Upvotes: 1

Views: 74

Answers (3)

Ziyad Moraished
Ziyad Moraished

Reputation: 361

Try this:

df1= df1[df1['Count1'] < 5 & df1['Count2'] < 5]

Upvotes: 1

jezrael
jezrael

Reputation: 862581

Use mask:

df[['Count1','Value1']] = df[['Count1','Value1']].mask(df.Count1 < 5)
df[['Count2','Value2']] = df[['Count2','Value2']].mask(df.Count2 < 5)

print (df)
    ID  Count1  Value1  Count2  Value2
0  111     5.0    10.0     5.0    25.0
1  112     NaN     NaN     6.0    25.0
2  113     6.0     7.0     NaN     NaN
3  114     NaN     NaN     NaN     NaN
4  115     7.0     1.0     8.0    10.0

Upvotes: 1

Vaishali
Vaishali

Reputation: 38415

Using loc

df.loc[df['Count1'] < 5, ['Count1','Value1']] = np.nan
df.loc[df['Count2'] < 5, ['Count2','Value2']] = np.nan

    ID  Count1  Value1  Count2  Value2
0   111 5.0     10.0    5.0     25.0
1   112 NaN     NaN     6.0     25.0
2   113 6.0     7.0     NaN     NaN
3   114 NaN     NaN     NaN     NaN
4   115 7.0     1.0     8.0     10.0

Upvotes: 2

Related Questions