Skip to content Skip to sidebar Skip to footer

Python - Pandas Dataframe With Multiple Names Per Column

Is there a way in pandas to give the same column of a pandas dataframe two names, so that I can index the column by only one of the two names? Here is a quick example illustrating

Solution 1:

You can create a multi-index column:

df.columns = pd.MultiIndex.from_tuples(df.columns)

Then you can do:

df.loc[:, ("A", slice(None))]

enter image description here

Or: df.loc[:, (slice(None), "B")]

Here slice(None) is equivalent to selecting all indices at the level, so (slice(None), "B") selects columns whose second level is B regardless of the first level names. This is semantically the same as :. Or write in pandas index slice way. df.loc[:, pd.IndexSlice[:, "B"]] for the second case.

Post a Comment for "Python - Pandas Dataframe With Multiple Names Per Column"