简体   繁体   中英

How to remove values that do not meet condition from pandas data frame column?

How can I remove under age rows from this data set?

Original dataset

ID                 age
xqd26543231        12
xqd22222231        29
xqd88823231        64

What I tried?

#remove under age users
eligibleAge = myDataFrame['Age']>18
myDataFrame['Age'] = myDataFrame[eligibleAge]

Unexpected result

ID                 age
xqd26543231        xqd26543231
xqd22222231        xqd22222231
xqd88823231        xqd88823231

What I expect

ID                 age
xqd22222231        29
xqd88823231        64

I think you can just do myDataFrame = myDataFrame[myDataFrame['Age']>18]

In your code, myDataFrame['Age'] = myDataFrame[eligibleAge] right side has different length as left size you are assigning to, and also you are assigning a dataframe onto a serie.

You can use df.query here.

df.query('age>18')
            ID  age
1  xqd22222231   29
2  xqd88823231   64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM