One Liners with Python

Nandini
2 min readJul 21, 2022

We all are searching for our perfect one-liners. You have landed in the perfect place. Let’s solve those common python data problems.

Our Dataset:

I am adding the image of the dataset that we will be using in this article. This is our data frame df.

Reset index column

Suppose we want to set the index of our columns by Product Category, we can do it with:

df_ind = df.set_index(“Product Category”)
df_ind.head()

Result

Reindex and sort by two columns

df_ind = df.set_index([“Product Category”,”Product Subcategory”])

df_ind = df_ind.sort_index(level=[“Product Category”,”Product Subcategory”],ascending=[False, True])

df_ind

Filter Dataframe by a value in a particular column.

Suppose we want to filter the data and only keep rows where the product subcategory is ‘Sweet’, here’s how you do it.

df_filter = (df[df[‘Product Subcategory’] == ‘Sweets’])
df_filter

Result

Calculate the range of a column.

def range(column):
return column.max() — column.min()

print(df[[‘Price’, ‘Age’]].agg(range))

Result:

That’s all Folks. Keep checking your One liner here!! Please subscribe and keep checking.

--

--