Python 带seaborn的Jointplot多索引列

Python 带seaborn的Jointplot多索引列,python,pandas,matplotlib,seaborn,pandas-groupby,Python,Pandas,Matplotlib,Seaborn,Pandas Groupby,我有这个数据框: df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B', 'B'], 'col2': ['A1', 'B1', 'B1', 'B1', 'A1']}) col1 col2 0 A A1 1 A B1 2 B B1 3 B B1 4 B A1 我做了一个群比。结果是一个多索引列 df = df.groupby(['col1']).agg({'col2': ['nuni

我有这个数据框:

df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B', 'B'], 'col2': ['A1', 'B1', 'B1', 'B1', 'A1']})

              col1  col2

0   A   A1
1   A   B1
2   B   B1
3   B   B1
4   B   A1
我做了一个群比。结果是一个多索引列

df = df.groupby(['col1']).agg({'col2': ['nunique','count']})

       col2
       nunique   count
 col1       
 A     2           2
 B     2           3
然后,我在seaborn图书馆做了一个拼接图

sns.jointplot(x=['col2','nunique'],y=['col2','count'],data=df,kind='scatter')
我犯了这个错误

TypeError: only integer scalar arrays can be converted to a scalar index
我的问题是:

有没有办法像这样将多索引列拆分为两个独立的列

col1  col2_unique col2_count        
 A     2           2
 B     2           3

有什么方法可以连接多索引列吗


谢谢你的帮助

您可以通过在列表中指定列
col2
和在
agg
中为列中的避免
MultiIndex
仅使用聚合函数来更改聚合:

df = df.groupby(['col1'])['col2'].agg(['nunique','count'])
print(df)
      nunique  count
col1                
A           2      2
B           2      3

sns.jointplot(x='nunique', y='count', data=df, kind='scatter')

或者,如果需要,在
agg
中使用
dictionary
,将多索引展平,例如,聚合另一列:

df = df.groupby(['col1']).agg({'col2': ['nunique','count'], 'col1':['min']})

df.columns = df.columns.map('_'.join)
print (df)
     col1_min  col2_nunique  col2_count
col1                                   
A           A             2           2
B           B             2           3