如何获取表中频繁值较低的行的索引

2024-09-26 22:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获取具有较少计数值的行的索引。例如:

test = pd.DataFrame({'price' : [1, 2, 1, 3, 5, 2, 2]})
out[1]:
    price
0   1
1   2
2   1
3   3
4   5
5   2
6   2

如何得到price=1,3,5的指数,它在列中只出现了不到3次?你知道吗


Tags: testdataframe指数outprice数值pd少计
2条回答

您可以用value_counts数一数项目,然后选择那些“足够罕见”的项目:

THRESHOLD = 3
is_rare = test['price'].value_counts() < THRESHOLD
rare = is_rare[is_rare].index
#Int64Index([1, 5, 3], dtype='int64')

接下来,查找包含稀有项的行:

are_rare_rows = test["price"].isin(rare)
are_rare_rows[are_rare_rows].index
#Int64Index([0, 2, 3, 4], dtype='int64')

使用duplicated

test[~test.price.duplicated(keep=False)]
   price
3      3
4      5

test.index[~test.price.duplicated(keep=False)]
Int64Index([3, 4], dtype='int64')

更新然后你需要transform

test[test.groupby('price').price.transform('count')<=1]
   price
3      3
4      5

test[test.groupby('price').price.transform('count')<3].index
Int64Index([0, 2, 3, 4], dtype='int64')

相关问题 更多 >

    热门问题