如何构造属性属于某个范围的 Python 熊猫系列对象



我有一只熊猫。对象的系列S,其中每个对象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 的代码,但它会产生一个错误,即: 类型错误:列表索引必须是整数或切片,而不是序列

import numpy as np
import pandas as pd
class Object:
def __init__(self, tid, length):
self.tid = tid        
self.len = length
objectseries = 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])

您可以使用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

最新更新