使用 seaborn 的 Jointplot 多索引列
Posted
技术标签:
【中文标题】使用 seaborn 的 Jointplot 多索引列【英文标题】:Jointplot multiindex columns with seaborn 【发布时间】: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
或
有没有办法联合绘制多索引列?
感谢您的帮助!
【问题讨论】:
【参考方案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
【讨论】:
以上是关于使用 seaborn 的 Jointplot 多索引列的主要内容,如果未能解决你的问题,请参考以下文章