gpt4 book ai didi

python - 带有 seaborn 的 Jointplot 多索引列

转载 作者:行者123 更新时间:2023-12-05 06:35:37 25 4
gpt4 key购买 nike

我有这个数据框:

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

我做了一个groupby。结果是一个多索引列

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

col2
nunique count
col1
A 2 2
B 2 3

然后,我从 seaborn 库中做了一个 jointplot

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 中使用 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

关于python - 带有 seaborn 的 Jointplot 多索引列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49671050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com