python - How to groubpy with hierarchical columns? -


i have dataframe multi-level columns, , not able find way groupby columns. there addressing columns or should go route of joining names in this question?

solution: addressing columns ['a','x'] instead of ('a','x')

you can still use .groupby on columns. below simple example.

import pandas pd import numpy np  # data # ========================================== np.random.seed(0) multi_col = pd.multiindex.from_product([['a', 'b'], ['x', 'y']], names=['ab', 'xy']) df = pd.dataframe(np.random.randint(1,5, (10,4)), columns=multi_col) df  ab      b    xy  x  y  x  y 0   1  4  2  1 1   4  4  4  4 2   2  4  2  3 3   1  4  3  1 4   1  1  3  2 5   3  4  4  3 6   1  2  2  2 7   2  1  2  1 8   4  1  4  2 9   3  4  4  1  # groupby 1 column # =================================== g_name, g in df.groupby([('a', 'x')]):     print(g_name)     print(g)   1 ab      b    xy  x  y  x  y 0   1  4  2  1 3   1  4  3  1 4   1  1  3  2 6   1  2  2  2 2 ab      b    xy  x  y  x  y 2   2  4  2  3 7   2  1  2  1 3 ab      b    xy  x  y  x  y 5   3  4  4  3 9   3  4  4  1 4 ab      b    xy  x  y  x  y 1   4  4  4  4 8   4  1  4  2       # groupby 2 columns # =================================== g_name, g in df.groupby([('a','x'), ('a','y')]):     print(g_name)     print(g)  (1, 1) ab      b    xy  x  y  x  y 4   1  1  3  2 (1, 2) ab      b    xy  x  y  x  y 6   1  2  2  2 (1, 4) ab      b    xy  x  y  x  y 0   1  4  2  1 3   1  4  3  1 (2, 1) ab      b    xy  x  y  x  y 7   2  1  2  1 (2, 4) ab      b    xy  x  y  x  y 2   2  4  2  3 (3, 4) ab      b    xy  x  y  x  y 5   3  4  4  3 9   3  4  4  1 (4, 1) ab      b    xy  x  y  x  y 8   4  1  4  2 (4, 4) ab      b    xy  x  y  x  y 1   4  4  4  4 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -