【问题标题】:Seaborn barplot: isna is not defined for MultiIndexSeaborn barplot:没有为 MultiIndex 定义 isna
【发布时间】:2021-09-03 13:44:50
【问题描述】:

我想使用 seaborn barplot() 从多索引系列创建条形图。我将我的数据集按两个变量分组:

module_7_a_df = module_7_df.groupby(by=['Reported Race "MONRACE"', 'Hispanic Origin "HISPORIG"'])['SENTENCE CAP "SENSPCAP"'].count()

对数据框进行分组会创建一个系列。这是生成的系列的样子:

当我尝试创建条形图时,我不断收到一条错误消息,指出“没有为 MultiIndex 定义 isna。”条形图的代码是:

sns.barplot(x=module_7_a_df.values, y=module_7_a_df.index)

此代码适用于数据仅按一列分组的系列。

有人能理解如何处理这个错误吗?

【问题讨论】:

    标签: python pandas seaborn series


    【解决方案1】:

    在分组之前从您分组的列中删除所有 nan 值。

    module_7_a_df.dropna(subset=['Reported Race "MONRACE"', 'Hispanic Origin "HISPORIG"'])
    

    【讨论】:

      【解决方案2】:

      当你有一个多索引时,你需要reset_index 和当使用hue = 来启用分组,使用示例数据集:

      import pandas as pd
      import seaborn as sns
      
      df = sns.load_dataset("tips")
      counts = df.groupby(['time','day']).size()
      
      counts
      
      time    day 
      Lunch   Thur    61
              Fri      7
              Sat      0
              Sun      0
      Dinner  Thur     1
              Fri     12
              Sat     87
              Sun     76
      dtype: int64
      

      然后使用以下内容:

      counts = counts.to_frame('counts').reset_index()
      sns.barplot(data = counts, x = "time",y="counts",hue="day")
      

      【讨论】:

        猜你喜欢
        • 2020-06-27
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        • 2017-08-30
        • 2021-03-04
        相关资源
        最近更新 更多