如果值计数低于阈值,则将列值映射为“其他”-分类列-Pandas Dataframe

时间:2018-09-04 10:42:22

标签: python pandas

我有一个形状为[200K,40]的熊猫数据框。数据框具有一个分类列(众多列之一),具有超过1000个唯一值。我可以使用以下方法可视化每个此类唯一列的值计数:

element1
element2
stop element3
element3

我现在如何通过以下方式来体现价值观:

  • value_count小于阈值(例如100),并将其映射为“其他”?
  • 基于累积行数%的OR?

3 个答案:

答案 0 :(得分:3)

您可以从value_counts的索引中提取要掩盖的值,并使用replace将它们映射到“其他”:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 10, (2000, 2)), columns=['A', 'B'])

frequencies = df['A'].value_counts()

condition = frequencies<200   # you can define it however you want
mask_obs = frequencies[condition].index
mask_dict = dict.fromkeys(mask_obs, 'miscellaneous')

df['A'] = df['A'].replace(mask_dict)  # or you could make a copy not to modify original data

现在,使用value_counts将所有低于阈值的值归为杂项:

df['A'].value_counts()

df['A'].value_counts()
Out[18]: 
miscellaneous    947
3                226
1                221
0                204
7                201
2                201

答案 1 :(得分:1)

我认为需要:

df = pd.DataFrame({ 'A': ['a','a','a','a','b','b','b','c','d']})

s = df['A'].value_counts()
print (s)
a    4
b    3
d    1
c    1
Name: A, dtype: int64

如果需要对threshold以下的所有值求和:

threshold = 2

m = s < threshold
#filter values under threshold
out = s[~m]
#sum values under and create new values to Series
out['misc'] = s[m].sum()
print (out)
a       4
b       3
misc    2
Name: A, dtype: int64

但是如果需要rename索引值,则必须低于阈值:

out = s.rename(dict.fromkeys(s.index[s < threshold], 'misc'))
print (out)
a       4
b       3
misc    1
misc    1
Name: A, dtype: int64

如果需要替换原始列,请使用GroupBy.transformnumpy.where

df['A'] = np.where(df.groupby('A')['A'].transform('size') < threshold, 'misc', df['A'])
print (df)

      A
0     a
1     a
2     a
3     a
4     b
5     b
6     b
7  misc
8  misc

答案 2 :(得分:0)

替代解决方案:

cond = df['col'].value_counts()
threshold = 100
df['col'] = np.where(df['col'].isin(cond.index[cond >= threshold ]), df['col'], 'miscellaneous')