python - 如何构造属性在某个范围内的 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])
解决方案
您可以使用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
推荐阅读
- python - 如何在大图中定位二维码以提高解码性能?
- php - 如何使用 php 访问 Gutenberg “core-embed/youtube”
- spring - Spring Integration - RoundRobin 和 Failover 的两个永久连接
- machine-learning - Ktrain |我的模型在训练期间在训练/验证数据上表现良好,但在测试数据上没有
- python - 使用 python 在 selenium 中修改 div 的类
- amadeus - 如何创建带有额外行李/座位的订单
- entity-framework-core - Blazor 应用程序:登录后更改数据库连接
- sql - 显示具有不同值的行
- python - 是否可以在 Python 中迭代单个键值对以将值打印到列表中?
- reactjs - 将无状态父组件的点击发送到子组件