pandas基础3

第三章
目前阔以理解,熟练度待提高
(a) 极差为17561
df = pd.read_csv(‘data/Diamonds.csv’)
df.head()

df_r = df.query(‘carat>1’)[‘price’]
df_r.max()-df_r.min()

(b) 0-0.2分位数区间最多的为‘E’,其余区间都为‘G’

bins = df[‘depth’].quantile(np.linspace(0,1,6)).tolist()
cuts = pd.cut(df[‘depth’],bins=bins) #可选label添加自定义标签
df[‘cuts’] = cuts
df.head()

color_result = df.groupby(‘cuts’)[‘color’].describe()
color_result

前三个分位数区间不满足条件,后两个区间中数量最多的颜色的确是均重价格中最贵的

df[‘均重价格’]=df[‘price’]/df[‘carat’]
color_result[‘top’] == [i[1] for i in df.groupby([‘cuts’,‘color’])[‘均重价格’].mean().groupby([‘cuts’]).idxmax().values]
© 结果见下:
df = df.drop(columns=‘均重价格’)
cuts = pd.cut(df[‘carat’],bins=[0,0.5,1,1.5,2,np.inf]) #可选label添加自定义标签
df[‘cuts’] = cuts
df.head()

for name,group in df.groupby(‘cuts’):
group = group.sort_values(by=‘depth’)
s = group[‘price’]
print(name,f(s.tolist()))
(d) 计算结果如下:
for name,group in df[[‘carat’,‘price’,‘color’]].groupby(‘color’):
L1 = np.array([np.ones(group.shape[0]),group[‘carat’]]).reshape(2,group.shape[0])
L2 = group[‘price’]
result = (np.linalg.inv(L1.dot(L1.T)).dot(L1)).dot(L2).reshape(2,1)
print(‘当颜色为%s时,截距项为:%f,回归系数为:%f’%(name,result[0],result[1]))
第二题
(a)
df = pd.read_csv(‘data/Drugs.csv’)
df.head()

idx=pd.IndexSlice
for i in range(2010,2018):
county = (df.groupby([‘COUNTY’,‘YYYY’]).sum().loc[idx[:,i],:].idxmax()[0][0])
state = df.query(‘COUNTY == “%s”’%county)[‘State’].iloc[0]
state_true = df.groupby([‘State’,‘YYYY’]).sum().loc[idx[:,i],:].idxmax()[0][0]
if state==state_true:
print(‘在%d年,%s县的报告数最多,它所属的州%s也是报告数最多的’%(i,county,state))
else:
print(‘在%d年,%s县的报告数最多,但它所属的州%s不是报告数最多的,%s州报告数最多’%(i,county,state,state_true))
(b) OH州增加最多,Heroin是增量最大的,但增幅最大的是Acetyl fentanyl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值