简体   繁体   中英

How to eliminate rows in a dataframe by selecting a specific range for each column? - Pandas

I am working on a dataframe that displays information on property rentals in Brazil. This is a sample of the dataset:

data = {
    'city': ['São Paulo', 'Rio', 'Recife'],
    'area(m2)': [90, 120, 60],
    'Rooms': [3, 2, 4],
    'Bathrooms': [2, 3, 3],
    'animal': ['accept', 'do not accept', 'accept'],
    'rent($)': [2000, 3000, 800]}

df = pd.DataFrame(
    data,
    columns=['city', 'area(m2)', 'Rooms', 'Bathrooms', 'animal', 'rent($)'])

print(df)

This is how the sample looks:

        city  area(m2)  Rooms  Bathrooms         animal  rent($)
0  São Paulo        90      3          2         accept     2000
1        Rio       120      2          3  do not accept     3000
2     Recife        60      4          3         accept      800

I want to filter the dataset in order to select only the apartments that have at maximum 2 rooms and 2 bathrooms.

Do you know how I can do this?

Try with

out = df.loc[(df.Rooms>=2) & (df.Bathrooms>=2)]

You can use query() method:

out=test_gdata.query('Bathrooms<=2 and Rooms<=2')

You can filter the values on the dataframe

import pandas as pd 

data = {
    'city': ['São Paulo', 'Rio', 'Recife'],
    'area(m2)': [90, 120, 60],
    'Rooms': [3, 2, 4],
    'Bathrooms': [2, 3, 3],
    'animal': ['accept', 'do not accept', 'accept'],
    'rent($)': [2000, 3000, 800]}

df = pd.DataFrame(
    data,
    columns=['city', 'area(m2)', 'Rooms', 'Bathrooms', 'animal', 'rent($)'])

df_filtered = df[(df['Rooms'] <= 2) & (df['Bathrooms'] <= 2)]

print(df_filtered)

Returns

        city  area(m2)  Rooms  Bathrooms         animal  rent($)
0  São Paulo        90      3          2         accept     2000
1        Rio       120      2          3  do not accept     3000
2     Recife        60      4          3         accept      800

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