【问题标题】:Data Analysis with Pandas throws nothing使用 Pandas 进行数据分析没有任何结果
【发布时间】:2020-12-24 22:52:32
【问题描述】:

编写一个名为 ratio_of_education 的函数,它返回数据集中的孩子的比例,其母亲的教育水平等于低于高中 (12) 和大学学位。

这个函数应该以如下形式返回一个字典(使用正确的数字,不要四舍五入):

{"less than high school":0.2,
"high school":0.4,
"more than high school but not college":0.2,
"college":0.2}

我复制并尝试使用的代码如下

def proportion_of_education():
    # your code goes here
    # YOUR CODE HERE
    # raise NotImplementedError()
    import pandas as pd
    import numpy as np
    df = pd.read_csv("assests/NISPUF17.csv", index_col=0)
    EDUS=df['EDUC1']
    edus=np.sort(EDUS.values)
    poe={"less than high school":0,
        "high school":0,
        "more than high school but not college":0,
        "college":0}
    n=len(edus)
    poe["less than high school"]=np.sum(edus==1)/n
    poe["high school"]=np.sum(edus==2)/n
    poe["more than high school but not college"]=np.sum(edus==3)/n
    poe["college"]=np.sum(edus==4)/n
    return poe
assert type(proportion_of_education())==type({}), "You must return a dictionary."
assert len(proportion_of_education()) == 4, "You have not returned a dictionary with four items in it."
assert "less than high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "more than high school but not college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
assert "college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."

应该打印出来

{"less than high school":0.2,
    "high school":0.4,
    "more than high school but not college":0.2,
    "college":0.2}

但是,Notebook 什么也没抛出。不是错误,尽管我使用不同的路径多次运行它,但绝对没有打印出来。可能是什么问题。

【问题讨论】:

  • 您可以更好地创建字典。也许像poe = df['EDU'].value_counts(normalize=True).to_dict(); return poe;
  • 此外,这里似乎只有断言,但没有“打印”语句(如果你想“打印”某些东西,你需要拥有的东西)。
  • 在普通脚本/程序中,您必须使用 print() 来显示任何内容 - print(proportion_of_education()) 或分两步 results = proportion_of_education() print(results)。在笔记本中你也可以使用print(...) 或者至少你必须在没有任何其他元素的情况下执行函数 - proportion_of_education() - 并且笔记本应该自动显示单元格中最后一个函数的结果。但是您在 assert 中使用 proportion_of_education() 会从函数中获取结果,因此 Notebook 没有可显示的内容。

标签: python pandas data-analysis


【解决方案1】:

您应该使用len(edus==1) 而不是np.sum,并且与其他人类似

【讨论】:

    【解决方案2】:

    df = pd.read_csv("assests/NISPUF17.csv", index_col=0) 您必须将此行替换为下面的行,因为您编写了错误的资产拼写。

    df = pd.read_csv("assets/NISPUF17.csv", index_col=0)

    【讨论】:

      【解决方案3】:

      正确的代码是:

      import pandas as pd
      import numpy as np
      
      def proportion_of_education():
          
          df = pd.read_csv("assets/NISPUF17.csv", index_col = 0)
          
          EDUS = df['EDUC1']
          edus = np.sort(EDUS.values)
          
          poe = {"less than high school": 0,
              "high school": 0,
              "more than high school but not college": 0,
              "college": 0}
          n = len(edus)
          
          poe["less than high school"] = np.sum(edus == 1)/n
          poe["high school"] = np.sum(edus == 2)/n
          poe["more than high school but not college"] = np.sum(edus == 3)/n
          poe["college"] = np.sum(edus == 4)/n
          
          return poe
          raise NotImplementedError()
      

      【讨论】:

        【解决方案4】:

        将熊猫导入为 pd 将 numpy 导入为 np

        def ratio_of_education():

        # your code goes here
        # YOUR CODE HERE
        
        df = pd.read_csv(r'assets/NISPUF17.csv',index_col=0)
        EDUC1 = df['EDUC1']
        educ1 = np.sort(EDUC1.values)
        poe = {"less than high school": 0,
            "high school": 0,
            "more than high school but not college": 0,
            "college": 0}
        total = len(educ1)
        poe['less than high school'] = len(df[df['EDUC1'] == 1])/total
        poe['high school'] = len(df[df['EDUC1'] == 2])/total
        poe['more than high school but not college'] = len(df[df['EDUC1'] == 3])/total
        poe['college'] = len(df[df['EDUC1'] == 4])/total
        return poe
        raise NotImplementedError()
        

        proportion_of_education()

        【讨论】:

          【解决方案5】:

          在问题下方的第一个单元格中键入以读取数据

          import pandas as pd
          df=pd.read_csv('assets/NISPUF17.csv',index_col=0)
          df
          

          在下一个单元格中

          def proportion_of_education():
              # your code goes here
              cat=pd.value_counts(df['EDUC1'])
              total=sum(cat)
              a_dict=dict(cat)
              s=pd.Series(a_dict)
              f=lambda x: x/total
              s=s.apply(f)
              s_dict=dict(s)
              s_dict['less than high school'] = s_dict.pop(1)
              s_dict['high school'] = s_dict.pop(2)
              s_dict['more than high school but not college'] = s_dict.pop(3)
              s_dict['college'] = s_dict.pop(4)
              return s_dict
          
              raise NotImplementedError()
          

          要检查,请在下一个单元格中输入此内容

          proportion_of_education()
          

          这个问题的最后一个单元格在下面

          assert type(proportion_of_education())==type({}), "You must return a dictionary."
          assert len(proportion_of_education()) == 4, "You have not returned a dictionary with four items in it."
          assert "less than high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
          assert "high school" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
          assert "more than high school but not college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
          assert "college" in proportion_of_education().keys(), "You have not returned a dictionary with the correct keys."
          

          在“EDUC1”列中,会有 1 2 3 4

          => 1 - 低于高中

          => 2 - 高中

          => 3 - 超过高中但不是大学

          => 4 - 大学

          lambda 函数用于计算所有类别的比例

          .pop() 方法用于将 1 重命名为 高中以下,其他类别也类似

          【讨论】:

            【解决方案6】:
                import pandas as pd
                import numpy as np
                def proportion_of_education():
                # your code goes here
                # YOUR CODE HERE
                    df=pd.read_csv('assets/NISPUF17.csv',index_col=0)
                    poe = {"less than high school": len(df[df['EDUC1'] == 1])/len(df),
            "high school": len(df[df['EDUC1'] == 2])/len(df),
            "more than high school but not college": len(df[df['EDUC1'] == 3])/len(df),
            "college": len(df[df['EDUC1'] == 4])/len(df)}
                  return poe
            
            
                proportion_of_education()
            

            【讨论】:

            • 欢迎来到 StackOverflow!感谢您的贡献,虽然此代码可能会回答问题,但包含解释会更有帮助。此外,您有一些缩进错误,因此代码可能无法完全按照发布的那样工作。
            【解决方案7】:

            简单的解决方案

            def proportion_of_education():
                import pandas as pd
            
            
                df = pd.read_csv("NISPUF17.csv")
            
                df = df["EDUC1"]
                lessThanHighSchool = (df[df == 1].count()) / df.count()
                highScool = (df[df == 2].count()) / df.count()
                moreThanHighSchoolNotCollage = (df[df == 3].count()) / df.count()
                collage = (df[df == 4].count()) / df.count()
            
                dictionary = {"less than high school ":lessThanHighSchool ,
                    "high school":highScool,
                    "more than high school but not college":moreThanHighSchoolNotCollage,
                    "college":collage
                    }
            
                return dictionary
            

            【讨论】:

            • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
            猜你喜欢
            • 2018-09-25
            • 2013-06-11
            • 1970-01-01
            • 1970-01-01
            • 2014-06-10
            • 1970-01-01
            • 2018-06-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多