python - Convert dataframe columns to MultiIndex -
how convert existing dataframe single-level columns have hierarchical index columns (multiindex)?
example dataframe:
in [1]: import pandas pd pandas import series, dataframe df = dataframe(np.arange(6).reshape((2,3)), index=['a','b'], columns=['one','two','three']) df out [1]: 1 2 3 0 1 2 b 3 4 5
i'd have thought reindex() work, nan's:
in [2]: df.reindex(columns=[['odd','even','odd'],df.columns]) out [2]: odd odd 1 2 3 nan nan nan b nan nan nan
same if use dataframe():
in [3]: dataframe(df,columns=[['odd','even','odd'],df.columns]) out [3]: odd odd 1 2 3 nan nan nan b nan nan nan
this last approach work if specify df.values:
in [4]: dataframe(df.values,index=df.index,columns=[['odd','even','odd'],df.columns]) out [4]: odd odd 1 2 3 0 1 2 b 3 4 5
what's proper way this? why reindex() give nan's?
you close, set columns directly new (equal sized) index-like (which if list-of-list convert multi-index)
in [8]: df out[8]: 1 2 3 0 1 2 b 3 4 5 in [10]: df.columns = [['odd','even','odd'],df.columns] in [11]: df out[11]: odd odd 1 2 3 0 1 2 b 3 4 5
reindex reorder / filter existing index. reason nans saying, hey find existing columns match new index; none match, that's get
Comments
Post a Comment