How to do Multi-Column from_tuples?
Assign direct to columns
with the result from pd.MultiIndex.from_tuples
passing in your existing columns:
In [186]:l=[('A', 'a'), ('A', 'b'), ('B','a'), ('B','b')]df = pd.DataFrame(np.random.randn(5,4), columns = l)dfOut[186]: (A, a) (A, b) (B, a) (B, b)0 -0.876353 0.553742 1.631858 -0.5613091 0.463058 -0.455014 -0.491336 -1.4360592 0.337810 0.233624 -0.571749 -2.2597633 1.073057 -0.475894 0.999643 -0.3797434 0.441800 0.311202 -0.191552 0.291268In [187]: df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Lower'])dfOut[187]:Caps A B Lower a b a b0 -0.876353 0.553742 1.631858 -0.5613091 0.463058 -0.455014 -0.491336 -1.4360592 0.337810 0.233624 -0.571749 -2.2597633 1.073057 -0.475894 0.999643 -0.3797434 0.441800 0.311202 -0.191552 0.291268
note that you can assign directly to names
attribute of the columns
attribute like the following:
df.columns.names = ['Caps','Lower']
not to be confused with the name
attribute
Another solution is use MultiIndex.from_tuples
with parameter names
:
import pandas as pddf = pd.DataFrame({'Value': [1,2,3]}, index=[('A','a'),('B','a'),('B','b')])print (df) Value(A, a) 1(B, a) 2(B, b) 3df.index = pd.MultiIndex.from_tuples(df.index, names=['Caps','Lower'])print (df) ValueCaps Lower A a 1B a 2 b 3
This same works with columns
, see Edchum's answer
:
df.columns= pd.MultiIndex.from_tuples(df.columns, names=['Caps','Lower'])