【发布时间】: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