In MultiIndex dataframe:
JavaScript
x
5
1
import pandas as pd
2
a = [['a', 'b', 2, 3], ['c', 'b', 5, 6], ['a','c', 8, 9]]
3
df = pd.DataFrame(a, columns=['I1', 'I2', 'v1', 'v2'])
4
df = df.groupby(['I1', 'I2']).first()
5
I want to insert a row ex
at top and keep the first level of MultiIndex hidden. The expected result is
I tried concat
:
JavaScript
1
4
1
data_ex = {'v1':[99], 'v2': [98]}
2
df_ex = pd.DataFrame(data_ex, index = [('ex','ex')])
3
pd.concat([df_ex, df])
4
However it become
I also tried first concat without index, then groupby multiply index. But pandas will automatically sort by MultiIndex. As a result, ex row cannot be set at top.
Advertisement
Answer
You need pass the correct index format
JavaScript
1
11
11
1
df_ex = pd.DataFrame(data_ex, index = pd.MultiIndex.from_tuples([('ex','ex')],names=["I1", "I2"]))
2
3
pd.concat([df_ex, df])
4
Out[783]:
5
v1 v2
6
I1 I2
7
ex ex 99 98
8
a b 2 3
9
c 8 9
10
c b 5 6
11