🐍 Data Analyst Interview Series: Part 33
Part 33: Advanced Pandas: Query, Pipe, Cut, Qcut, Explode & More
Guys, let's continue our Python Interview Series. Today, we'll explore more advanced Pandas functions that are useful for real-world data analysis.
1️⃣ What is query() in Pandas?
Sample Answer:
query() allows us to filter rows using a readable expression instead of writing multiple conditions with Boolean indexing.
Example:
df.query("salary > 50000")
Multiple conditions:
df.query("salary > 50000 and age < 30")
2️⃣ What is the difference between loc[] and query()?
• loc[] is label-based indexing and supports flexible row and column selection.
• query() is mainly used to filter rows using expressions.
df.loc[df["salary"] > 50000]
df.query("salary > 50000")
Both can filter rows based on conditions.
3️⃣ What is pipe() in Pandas?
pipe() allows us to pass a DataFrame through multiple functions in a clean and readable way.
def filter_data(df):
return df[df["salary"] > 50000]
def sort_data(df):
return df.sort_values("salary", ascending=False)
result = (
df.pipe(filter_data)
.pipe(sort_data)
)
It helps organize complex data-cleaning workflows.
4️⃣ What is the difference between cut() and qcut()?
Both functions divide continuous numerical data into categories.
• cut() creates bins based on specified value ranges.
• qcut() creates bins based on quantiles, aiming for approximately equal numbers of observations per bin.
df["age_group"] = pd.cut(
df["age"],
bins=[0, 18, 35, 60, 100],
labels=["Child", "Young", "Adult", "Senior"]
)
Using qcut():
df["salary_group"] = pd.qcut(
df["salary"],
q=4,
labels=["Low", "Medium", "High", "Very High"]
)
5️⃣ What is explode() in Pandas?
explode() converts elements in a list-like column into separate rows.
df = pd.DataFrame({
"employee": ["A", "B"],
"skills": [
["Python", "SQL"],
["Excel", "Power BI"]
]
})
result = df.explode("skills")
Each skill gets its own row while the employee name is repeated.
6️⃣ What is get_dummies() in Pandas?
get_dummies() converts categorical variables into indicator columns, commonly used for one-hot encoding.
df = pd.DataFrame({
"department": ["HR", "IT", "Finance", "IT"]
})
encoded = pd.get_dummies(
df,
columns=["department"],
dtype=int
)
It creates separate columns for each department category.
7️⃣ What is the difference between astype() and to_numeric()?
• astype() converts a column into a specified data type.
• pd.to_numeric() specifically converts values into numeric types and can handle invalid values using errors="coerce".
df["age"] = df["age"].astype("int64")
Using to_numeric():
df["sales"] = pd.to_numeric(
df["sales"],
errors="coerce"
)
Invalid numeric values become NaN when using errors="coerce".
8️⃣ How do you find the top N records in a DataFrame?
We can use nlargest() or nsmallest().
top_5 = df.nlargest(5, "sales")
For the lowest five sales:
bottom_5 = df.nsmallest(5, "sales")
These methods are useful for quickly identifying top-performing or underperforming records.
9️⃣ How do you calculate the difference between two columns?
We can directly subtract one column from another.
df["profit"] = (
df["revenue"] - df["cost"]
)
To calculate profit margin: