Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - Dataframe filtering rows by column values

I have a Dataframe df

       Num1   Num2 
one       1      0
two       3      2
three     5      4
four      7      6
five      9      8

I want to filter rows that have value bigger than 3 in Num1 and smaller than 8 in Num2.

I tried this

df = df[df['Num1'] > 3 and df['Num2'] < 8]

but the error occurred.

ValueError: The truth value of a Series is ambiguous.

so I used

df = df[df['Num1'] > 3]
df = df[df['Num2'] < 8]

I think the code can be shorter.

Is there any other way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need add () because operator precedence with bit-wise operator &:

df1 = df[(df['Num1'] > 3) & (df['Num2'] < 8)]
print (df1)
       Num1  Num2
three     5     4
four      7     6

Better explanation is here.

Or if need shortest code use query:

df1 = df.query("Num1 > 3 and Num2 < 8")
print (df1)
       Num1  Num2
three     5     4
four      7     6

df1 = df.query("Num1 > 3 &  Num2 < 8")
print (df1)
       Num1  Num2
three     5     4
four      7     6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...