Reputation: 21
This is the input csv and the 4 header rows are becoming header for last 4 columns but I want that 1 header becomes header for first 4 columns (Client, DII, FII and Pro). Likewise 2nd header for another 4 columns in CSV format in pandas dataframe:-
How to create 4 header rows such that it occupies 4 cells?
Upvotes: 2
Views: 63
Reputation: 20669
You can use np.repeat
with pd.MultiIndex.from_tuples
a = np.repeat(['X','Y'],2)
df.columns = pd.MultiIndex.from_tuples(zip(a,df.columns))
df
X Y
A B C D
0 1 1 1 1
1 2 2 2 2
2 3 3 3 3
3 4 4 4 4
Upvotes: 2
Reputation: 34056
You can use pd.MultiIndex
:
In [2965]: a = pd.MultiIndex.from_product([["X"], df.columns[:2]])
In [2966]: b = pd.MultiIndex.from_product([["Y"], df.columns[2:]])
In [2975]: df.columns = pd.MultiIndex.from_tuples(a.tolist() + b.tolist())
In [2976]: df
Out[2976]:
X Y
A B C D
0 1 1 1 1
1 2 2 2 2
2 3 3 3 3
3 4 4 4 4
Upvotes: 3