为了账号安全,请及时绑定邮箱和手机立即绑定

合并数据框后,无法访问该数据框的groupby对象的各个列

合并数据框后,无法访问该数据框的groupby对象的各个列

慕田峪4524236 2021-05-12 18:23:22
这个问题与此类似,但是有一个关键的区别-当将数据帧分组到bin中时,链接问题的解决方案无法解决问题。以下代码对2个变量的bin的相对分布进行箱线绘图会产生错误:import pandas as pdimport seaborn as snsraw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],         'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],         'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],         'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],        'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()df1.fillna(0, inplace=True)sns.boxplot(x='regiment', y='preTestScore', data=df1)---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-241-fc8036eb7d0b> in <module>()----> 1 sns.boxplot(x='regiment', y='preTestScore', data=df1)如果删除x和y参数,它会产生一个箱线图,但它不是我想要的箱线图:我该如何解决?我尝试了以下方法:df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()df1.fillna(0, inplace=True)df1 = df1.reset_index()df1这看起来不对。实际上,这不是正常的数据帧;如果我们打印出它的列,它不会显示regiment为一列,这就是为什么boxplot给出错误的原因ValueError: Could not interpret input 'regiment':df1.columns>>> Index(['regiment', 2, 3, 4, 24, 31], dtype='object', name='preTestScore')因此,如果我能以某种方式使regiment数据框成为一列,我认为我应该能够绘制preTestScorevs的箱线图regiment。我错了吗?
查看完整描述

1 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

如果reset_index()在dataframe上执行操作df1,则应获取要具有的数据框。


问题是您有一个所需的列(regiment)作为索引,因此您需要重置它并将其设置为另一列。


编辑:add_prefix在结果数据框中添加了适当的列名


样例代码:


import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt


raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 

        'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 

        'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 

        'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],

        'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])



df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()

df1.fillna(0, inplace=True)


df1 = df1.add_prefix('preTestScore ')  # <- add_prefix for proper column names


df2 = df1.reset_index()  # <- Here is reset_index()

cols = df2.columns


fig = plt.figure(figsize=(20,3))


count = 1

for col in cols[1:]:

    plt.subplot(1, len(cols)-1, count)

    sns.boxplot(x='regiment', y=col, data=df2)

    count+=1

输出:

//img1.sycdn.imooc.com//60acce1c000100f509860176.jpg

查看完整回答
反对 回复 2021-05-25
  • 1 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号