Querying DataFrames
What is data querying?
How do I query data in Pandas?
# import pandas with the socially accepted alias 'pd'
>>> import pandas as pd
# create a DataFrame from a dictionary
>>> df = pd.DataFrame.from_dict(
{
"product": ["a", "b", "c"],
"price": [9.87, 8.63, 6.45],
"color": ["green", "green", "blue"],
}
)
# data preview
>>> df
product price color
0 a 9.87 green
1 b 8.63 green
2 c 6.45 blue
# info
>>> df.info()
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
Column Non-Null Count Dtype
--- ------ -------------- -----
0 product 3 non-null str
1 price 3 non-null float64
2 color 3 non-null str
dtypes: float64(1), str(2)
memory usage: 204.0 bytes
# select the first two cases using a range of indices
# CAREFUL: .loc is label-based and INCLUDES the upper bound, so 0:2 is
# three rows, not two
>>> df.loc[0:2]
product price color
0 a 9.87 green
1 b 8.63 green
2 c 6.45 blue
# for the first two, either stop one label earlier ...
>>> df.loc[0:1]
product price color
0 a 9.87 green
1 b 8.63 green
# ... or use .iloc, which is positional and excludes the upper bound
>>> df.iloc[0:2]
product price color
0 a 9.87 green
1 b 8.63 green
# select the column "price" for the first two cases using a boolean array
>>> df.loc[0:2, "price"]
0 9.87
1 8.63
2 6.45
Name: price, dtype: float64
# select the columns "price" and "color" for all cases
>>> df.loc[:, ["price", "color"]]
price color
0 9.87 green
1 8.63 green
# select all cases for which the column "price" is greater than or equal to 8.00
>>> df.loc[df["price"] >= 8.00, ]
product price color
0 a 9.87 green
1 b 8.63 green
# select all cases for which the column "price" is less than 9.00 and
# "color" is equal to "green"
>>> df.loc[(df["price"] < 9.00) & (df["color"] == "green" ), ]
product price color
1 b 8.63 green
# select all cases for which the column "price" is less than to 9.00 and
# "color" is equal to "green"; also, keep the column "price" only
>>> df.loc[(df["price"] < 9.00) & (df["color"] == "green" ), "price"]
1 8.63
Name: price, dtype: float64