第一讲实操题
第一讲未布置实操题。
第二讲实操题
1. 请完善如下代码,使得其生成一个3行5列的DataFrame对象。
import pandas as pd
import numpy as np
d = pd.DataFrame(np.arange(15).____(3, 5))
答案:reshape
2. 请完善如下代码,生成一个带有’a’, ‘b’, ‘c’, ‘d’索引的DataFrame对象。
import pandas as pd
dict1 = {‘one’:[1, 2, 3, 4], ‘two’:[9, 8, 7, 6]}
d = pd.DataFrame(dict1 , _ = [‘a’, ‘b’, ‘c’, ‘d’])
答案:index
3. 补全如下代码,打印其中非NaN变量的数量。
import pandas as pd
import numpy as np
a = pd.DataFrame(np.arange(20).reshape(4,5))
b = pd.DataFrame(np.arange(16).reshape(4,4))
print((a+b).______())
正确答案:count
第三讲实操题
1. 补全如下代码,对生成的变量a在0轴上进行升序排列。
import pandas as pd
import numpy as np
a = pd.DataFrame(np.arange(20).reshape(4,5), index = ['z', 'w', 'y', 'x'])
a.____________()
正确答案:sort_index
2. 补全如下代码,对生成的变量a在第2列上进行数值升序排列。
import pandas as pd
import numpy as np
a = pd.DataFrame(np.arange(20).reshape(4,5), index = ['z', 'w', 'y', 'x'])
a.____________(1)
正确答案:sort_values
3. 补全如下代码,打印其中非NaN变量的数量。
import pandas as pd
import numpy as np
a = pd.DataFrame(np.arange(20).reshape(4,5))
b = pd.DataFrame(np.arange(16).reshape(4,4))
print((a+b).______())
正确答案:count
第四讲实操题
1. 爬取网页(http://www.fortunechina.com/fortune500/c/2019-07/22/content_339535.htm) 中的世界500强企业名单,并导出为excel文件。
代码如下:
# reference program
import re
import requests
import pandas as pd
from bs4 import BeautifulSoup
def get_web_page_table(website, table_css_selector, encoding="UTF-8", header=True):
# to crawl the web page
r = requests.get(website)
# to correct coding
r.encoding = encoding
# to create BS object for parse HTML
bs_obj = BeautifulSoup(r.text, 'lxml')
# first step: find the table
table = bs_obj.select(table_css_selector)[0]
row_data = []
for row in table.select("tr"):
row_data.append([item.text for item in row.select("td")])
row_data = []
for row in table.select("tr"):
# to add table header
if len(row.select("th")) > 0:
row_data.append([re.sub("\s", "", item.text) for item in row.select("th")])
else:
row_data.append([re.sub("\s", "", item.text) for item in row.select("td")])
if header:
return pd.DataFrame(row_data[1:], columns=row_data[0])
else:
return pd.DataFrame(row_data)
result = get_web_page_table("http://www.fortunechina.com/fortune500/c/2019-07/22/content_339535.htm", "#table1", encoding="UTF-8")
result.to_excel("result.xlsx", index=False)
2. 通过高德交通大地图(https://report.amap.com/index.do ),抓取2020年第一季度某个城市的拥堵延时指数。
代码如下:
# reference program
import requests
import pandas as pd
r = requests.get('https://report.amap.com/ajax/cityDailyQuarterly.do?cityCode=310000&year=2020&quarter=1')
pdata = pd.DataFrame(r.json())
pdata = pdata.rename(columns={"categories":"date", "serieData":"value"})
pdata.to_excel("result.xlsx", index=False)
第五讲实操题
1.根据讲义所用的数据集(dataset.dta),检验90-00年代和80-90年代的男性的平均身高是否存在显著差异?
代码如下:
import pandas as pd
rdata = pd.read_stata("./data/dataset.dta")
listBins = [1920,1950,1960,1970,1980,1990,2000] # 区间设置
listLabels = ['50年代前', '50-60年代', '60-70年代', '70-80年代', '80-90年代', '90-00年代'] # 对应的区间标签
rdata["period"] = pd.cut(rdata["birthyear"], bins=listBins, labels=listLabels, include_lowest=True)
male_height_90 = rdata.loc[(rdata["gender"]=="男") & (rdata["period"]=="90-00年代"), "height"]
male_height_80 = rdata.loc[(rdata["gender"]=="男") & (rdata["period"]=="80-90年代"), "height"]
tStat, pValue = scipy.stats.ttest_ind(male_height_90, male_height_80, equal_var = False) #run independent sample T-Test
print("P-Value:{0} T-Statistic:{1}".format(pValue,tStat)) #print the P-Value and the T-Statistic
2. 根据下图的数据,利用决策树回归,预测batgirl和riddler是好人还是坏人?可以点击此处下载训练数据和测试数据
代码如下:
import pandas as pd
import graphviz
from sklearn import tree
train_data = pd.read_csv("./data/hero_train.csv")
test_data = pd.read_csv("./data/hero_test.csv")
columns = ['class', 'name', 'sex', 'mask', 'cape', 'tie', 'ears', 'smokes']
X = train_data[columns[2:]]
y = train_data[columns[0]]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)
X_test = test_data[columns[2:]]
y_pred=clf.predict(X_test)
print(y_pred)
dot_data = tree.export_graphviz(clf, out_file=None, feature_names=columns[2:], class_names=["Bad","Good"], filled=True, rounded=True, special_characters=True)
graph = graphviz.Source(dot_data)
graph
第六讲实操题
1. 利用wage1数据集,在控制教育水平、工作经验以及工作经验平方的前提下,检验未婚女性的平均工资是否显著地低于未婚男性的平均工资。
代码如下:
import pandas as pd
import statsmodels.formula.api as smf
# import dataset
df = pd.read_stata("http://fmwww.bc.edu/ec-p/data/wooldridge/wage1.dta")
# ols
results = smf.ols(formula='lwage ~ educ + exper + expersq + female*married', data=df).fit()
print(results.summary(), '\n\n')
2. 利用wage2数据集,比较OLS和IV估计(用sibs作为educ的工具变量)估计得到的教育回报率的结果(不加其他控制变量)。
代码如下:
import patsy
import pandas as pd
from linearmodels.iv import IV2SLS
from linearmodels.iv import compare
# import dataset
df = pd.read_stata("http://fmwww.bc.edu/ec-p/data/wooldridge/wage2.dta")
y, X = patsy.dmatrices("lwage ~ educ + sibs", data=df, return_type="dataframe")
res_ols = IV2SLS(y, X[['Intercept','educ']], None, None).fit(cov_type='unadjusted')
print(res_ols)
res_second = IV2SLS(y, X['Intercept'], X['educ'], X['sibs']).fit(cov_type='unadjusted')
print(res_second)
print(compare({'OLS':res_ols, '2SLS':res_second}))
第七、八讲实操题
这两讲,由于讲师在课上带着学员进行了实操,所以不额外留实操题。
第九讲实操题
1. 案例中使用了One-Hot Encoding对原始数据的day_of_week进行编码,请写出不使用One-Hot Encoding,而是map函数完成以下转化的代码:
原始数据 |
转换后 |
mon |
0 |
tue |
1 |
wed |
2 |
thu |
3 |
fri |
4 |
代码如下:
df['day_of_week'].map({'mon': 0, 'tue': 1, ‘wed’:2, ‘thu’:3, ‘fri’:4}).astype('uint8')
2. 请写出在案例中加入决策树分类器进行参数优化的相关代码:
代码如下:
pipe_dt = Pipeline([('dt', DecisionTreeClassifier(random_state=random_state, max_features='auto'))])
grid_params_dt = [{
'dt__max_depth': [8, 10],
'dt__min_samples_leaf': [1, 3, 5, 7]
}]
gs_dt = GridSearchCV(pipe_dt, param_grid=grid_params_dt,
scoring='accuracy', cv=cv)
look_for = [gs_lr, gs_rf, gs_dt]
model_dict = {0:'Logistic_reg', 1:'RandomForest', 2:'DesionTree', }
第十讲实操题
1. 案例中如果int_rate字段是字符串形式的2.3%,请写出将其转换为浮点数的代码。
代码如下:
def s2f(rate):
return float(rate[:-1])
df['int_rate']=df_origin['int_rate'].apply(s2f)
2. 发现训练集输入模型进行训练后报错,需要检查‘loan_amnt’列是否存在nan缺失数据,请写出代码。
代码如下:
ind1 = np.where(np.isnan(df[loan_amount].values))[0]
print(ind1)