You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The MultiIndex.to_frame function is great for working with multi-indexes as a meta-dataframe. I find myself using this paradigm very often.
df = create_multiindex_df()
meta = df.columns.to_frame(index=False)
meta = filter_multiindex()
df.reindex(columns=convert_df_to_multiindex(df))
Having the convert_df_to_multiindex as a pd.MultiIndex method would be extremely complimentary to pd.MultiIndex.to_frame.
A simplified one-line implementation provided below, not including accounting for some corner case behaviors and discerning between series/frames vs Index/Multiindex.
# pd.Index
@classmethod
def from_frame(cls, df):
if not isinstance(df.squeeze(), pd.Series):
raise ValueError('DataFrame must be be single column')
return cls.from_series(df.squeeze())
@classmethod
def from_series(cls, s):
return cls(s, name=s.name)
# pd.MultiIndex
@classmethod
def from_frame(cls, df, squeeze=True):
"""
:param df
:param squeeze
Squeeze single level multiindex to be a regular index
"""
# just let column level names be the tuple of the meta df columns since they're not required to be strings
# columns = ['.'.join(col) for col in list(df)]
columns = list(df)
mi = cls.from_tuples(list(df.values), names=columns)
if squeeze:
if len(mi.levels) == 1:
return mi.levels[0][mi.labels[0]]
else:
return mi
else:
return mi
The MultiIndex.to_frame function is great for working with multi-indexes as a meta-dataframe. I find myself using this paradigm very often.
Having the
convert_df_to_multiindex
as a pd.MultiIndex method would be extremely complimentary topd.MultiIndex.to_frame
.A simplified one-line implementation provided below, not including accounting for some corner case behaviors and discerning between series/frames vs Index/Multiindex.
The text was updated successfully, but these errors were encountered: