-
-
Notifications
You must be signed in to change notification settings - Fork 19.4k
Closed
Description
Is your feature request related to a problem?
I whish the pandas drop function would let me drop combination of rows (or columns) in multiindex dataframes.
E.g., I have a multiindex dataframe like this
| Column 1 | Column 2 | ||
|---|---|---|---|
| Index 1 | Index 2 | ||
| A | a | 1 | 2 |
| b | 3 | 4 | |
| B | a | 5 | 6 |
| b | 7 | 8 |
And I want to drop only the Index combination (B, a).
With the current implementation of the drop function, this is not possible.
Describe the solution you'd like
Maybe adding an additional parameter called combination, which is a boolean value, could solve the problem.
When setting combination=True, the list-like label parameter could be recognized as the combination to drop, which would then result in
df = df.drop(labels=["B", "a"], axis=0, combination=True)
df| Column 1 | Column 2 | ||
|---|---|---|---|
| Index 1 | Index 2 | ||
| A | a | 1 | 2 |
| b | 3 | 4 | |
| B | b | 7 | 8 |
API breaking implications
I think adding the parameter would not break the API.
Describe alternatives you've considered
I have not considered alternatives
Additional context
For my problem, I implemented a function similar to the one below
def drop(df: pd.DataFrame, index1: Optional[str]=None, index2: Optional[int]=None) -> pd.DataFrame:
if index1 is None:
if index2 is None:
# if no index1 and index2 is defined, return the original dataframe
return df
else:
return df.drop(index2, level="Index2").sort_index()
else:
if index2 is None:
return df.drop(index1, level="Index1").sort_index()
else:
a = df.drop(index1, level="Index1")
b = pd.concat([df.loc[index1].drop(index2, level="Index2")], keys=[index1], names=["Index1"])
return pd.concat([a, b]).sort_index()