根据value_counts()更改pandas数据帧中的值

Tor*_*ren 4 python python-2.7 pandas

我有以下pandas数据帧:

import pandas as pd 
from pandas import Series, DataFrame

data = DataFrame({'Qu1': ['apple', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'egg'],
              'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', 'sausage', 'banana', 'banana', 'banana'],
              'Qu3': ['apple', 'potato', 'sausage', 'cheese', 'cheese', 'potato', 'cheese', 'potato', 'egg']})
Run Code Online (Sandbox Code Playgroud)

我想更改列中的值Qu1,Qu2,Qu3根据value_counts()当值数大或等于一定数目

例如对于Qu1

>>> pd.value_counts(data.Qu1) >= 2
cheese     True
potato     True
banana     True
apple     False
egg       False
Run Code Online (Sandbox Code Playgroud)

我想保持值cheese,potato,banana,因为每个数据都至少两次出场.

从价值观appleegg我想创造价值others

对于列Qu2没有更改:

>>> pd.value_counts(data.Qu2) >= 2
banana     True
apple      True
sausage    True
Run Code Online (Sandbox Code Playgroud)

附件中的最终结果 test_data

test_data = DataFrame({'Qu1': ['other', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'other'],
                  'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', 'sausage', 'banana', 'banana', 'banana'],
                  'Qu3': ['other', 'potato', 'other', 'cheese', 'cheese', 'potato', 'cheese', 'potato', 'other']})
Run Code Online (Sandbox Code Playgroud)

谢谢 !

ayh*_*han 10

我会创建一个相同形状的数据框,其中相应的条目是值计数:

data.apply(lambda x: x.map(x.value_counts()))
Out[229]: 
   Qu1  Qu2  Qu3
0    1    2    1
1    2    4    3
2    3    3    1
3    2    3    3
4    3    3    3
5    2    2    3
6    3    4    3
7    2    4    3
8    1    4    1
Run Code Online (Sandbox Code Playgroud)

并且,使用结果df.where返回相应条目小于2的"other":

data.where(data.apply(lambda x: x.map(x.value_counts()))>=2, "other")

      Qu1      Qu2     Qu3
0   other  sausage   other
1  potato   banana  potato
2  cheese    apple   other
3  banana    apple  cheese
4  cheese    apple  cheese
5  banana  sausage  potato
6  cheese   banana  cheese
7  potato   banana  potato
8   other   banana   other
Run Code Online (Sandbox Code Playgroud)