【问题标题】:Jointplot multiindex columns with seaborn使用 seaborn 的 Jointplot 多索引列
【发布时间】:2018-09-15 04:46:03
【问题描述】:

我有这个数据框:

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

有没有办法联合绘制多索引列?

感谢您的帮助!

【问题讨论】:

    标签: python pandas matplotlib seaborn pandas-groupby


    【解决方案1】:

    您可以通过在列表中指定列 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 中使用 dictinary 或展平 MultiIndex - 例如聚合另一列:

    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
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 2017-05-18
      • 2019-10-28
      • 2022-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2016-12-08
      • 2015-07-06
      相关资源
      最近更新 更多