首页 > 解决方案 > 如何构造属性在某个范围内的 Python pandas 系列对象

问题描述

我有一个 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 Series

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])

标签: pythonpandas

解决方案


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

推荐阅读