为了账号安全,请及时绑定邮箱和手机立即绑定

如何构造属性在某个范围内的 Python pandas 系列对象

如何构造属性在某个范围内的 Python pandas 系列对象

一只斗牛犬 2022-06-22 18:21:43
我有一个 pandas.Series 对象,其中每个对象 t 有几个属性,其中一个是它的长度 t.len。我想创建另一个系列 SL,其中包含 S 中长度在 S 中对象的第 60 个百分位和第 90 个百分位之间的那些对象。对此进行编码的最有效方法是什么?假设S = [t0, t1, t2, t3, t4, t5, t6, t7, t8, t9]是一系列 10 个对象。它们对应的长度列表是[15, 4, 10, 20, 3, 20, 13, 8, 14, 1]。第 60 个百分位长度为 13.4,第 90 个百分位长度为 20。那么SL = [t0, t3, t5, t8]下面是基于series.between的代码,但是会产生错误,即:TypeError: list indices must be integers or slices, not Seriesimport numpy as npimport pandas as pdclass Object:    def __init__(self, tid, length):        self.tid = tid                self.len = lengthobjectseries = pd.Series([Object(0, 15), Object(1, 4), Object(2, 10), Object(3, 20), Object(4, 3), Object(5, 20), Object(6, 13), Object(7, 8), Object(8, 14), Object(9, 1)])lenseries = pd.Series(x.len for x in objectseries)ll = np.percentile(lenseries, 60)uu = np.percentile(lenseries, 90)sl = lenseries.between(ll,uu)print (sl)objectlist = objectseries.tolist()print (objectlist[sl])
查看完整描述

1 回答

?
开满天机

TA贡献1786条经验 获得超13个赞

您可以使用quantile获取百分位值并使用between:


df = pd.DataFrame({'object':[f't{i}' for i in range(10)],

              'values':[15, 4, 10, 20, 3, 20, 13, 8, 14, 1]})


q60,q90 = df['values'].quantile([0.6, 0.9])


df.loc[df['values'].between(q60,q90), 'object']

输出:


0    t0

3    t3

5    t5

8    t8

Name: object, dtype: object您可以使用quantile获取百分位值并使用between:


df = pd.DataFrame({'object':[f't{i}' for i in range(10)],

              'values':[15, 4, 10, 20, 3, 20, 13, 8, 14, 1]})


q60,q90 = df['values'].quantile([0.6, 0.9])


df.loc[df['values'].between(q60,q90), 'object']

输出:


0    t0

3    t3

5    t5

8    t8

Name: object, dtype: object


查看完整回答
反对 回复 2022-06-22
  • 1 回答
  • 0 关注
  • 210 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号