Updated:
I have a huge dataframe, providing small version of it.
header = [np.array([' ',' ',' ','X','X','Y','Y']),
np.array(['A','B','C','D','E','F','G'])]
df = pd.DataFrame(columns=header)
df[' ','A'] = ['n','n','m','m','m','p']
df[' ','B'] = ['q','r','s','t','u','v']
df[' ','C'] = [5,6,7,8,9,4]
df['X','D'] = ['1.5','2.9','3.6','2.5','7.1','0.4']
df['X','E'] = ['0.7%','3.9%','3.2%','1.5%','4.1%','2.4%']
df['Y','F'] = ['ab','bc','cd','de','ef','gh']
df['Y','G'] = ['5.5','2.6','8.6','4.5','0.1','3.4']
df =df.style.hide_index()
In real, 'B' is getting dynamically generated from another dataframe and depending on value of 'B', 'A' is being populated manually.
I want to group my dataframe on column 'A' and sort the dataframe on column 'A' too
I tried this code:
def func(x):
return x.sort_values([('','A')],ascending=False)
dfResult = df.groupby([('','A')])
dfResult1 = dfResult.apply(func)
dfResult1
| | | | | X | Y
(,A) | | A | B | C | D | E | F | G
-----|---|---|---|---|----|------|------|----
n | 0 | n | q | 5 |1.5 | 0.7% | ab | 5.5
| 1 | n | r | 6 |2.9 | 3.9% | bc | 2.6
--- -|---|---|---|---|----|------|------|----
m | 2 | m | s | 7 |3.6 | 3.2% | cd | 8.6
| 3 | m | t | 8 |2.5 | 1.5% | de | 4.5
| 4 | m | u | 9 |7.1 | 4.1% | ef | 0.1
-----|---|---|---|---|----|------|------|----
p | 5 | p | v | 4 |0.4 | 2.4% | gh | 3.4
Expected output:
dfExpected = pd.DataFrame({(' ','C'): [5,6,7,8,9,4],
('X', 'D'): ['1.5','2.9','3.6','2.5','7.1','0.4'],
('X', 'E'): ['0.7%','3.9%','3.2%','1.5%','4.1%','2.4%'],
('Y', 'F'): ['ab','bc','cd','de','ef','gh'],
('Y', 'G'): ['5.5','2.6','8.6','4.5','0.1','3.4']},
index=pd.MultiIndex.from_arrays([['n','n','m','m','m','p'],
['q','r','s','t','u','v']],
names=['A', 'B']))
printing dfResult1 does not gives me the desired dataframe.
Also when I am applying styles on dfResult1, the grouping doesn't not exists anymore, it's taking the form of original dataframe after applying styles. I need to apply styles on my dataframe for the dashboard.
can anyone pls help?