繁体   English   中英

根据 value_counts() 条件更改 Pandas 单元格中的值

[英]Change values in Pandas cells based on value_counts() condition

如何根据条件更改熊猫数据框中特定列中的值。 这是我的数据框:

import pandas as pd

df = pd.DataFrame({'data':['lemon', 'apple', 'lemon', 'apple', 'apple', 'lemon', 'pear', 'apple', 
                            'pear', 'lemon', 'pear', 'orange', 'banana', 'banana', 'pear']})

     data
0    lemon
1    apple
2    lemon
3    apple
4    apple
5    lemon
6     pear
7    apple
8     pear
9    lemon
10    pear
11  orange
12  banana
13  banana
14    pear

计算每个元素:

lemon     4
apple     4
pear      4
banana    2
orange    1
Name: data, dtype: int64

如果 value_counts() 结果小于 4,如何将值更改为“其他”? 预期结果:

     data
0    lemon
1    apple
2    lemon
3    apple
4    apple
5    lemon
6     pear
7    apple
8     pear
9    lemon
10    pear
11  other
12  other
13  other
14    pear

使用Series.mask与计数值Series.mapSeries.value_counts如果不像测试4

df['data'] = df['data'].mask(df['data'].map(df['data'].value_counts()).lt(4), 'other')
#alternative
df['data'] = df['data'].mask(df.groupby('data')['data'].transform('size').lt(4), 'other')
print (df)
     data
0   lemon
1   apple
2   lemon
3   apple
4   apple
5   lemon
6    pear
7   apple
8    pear
9   lemon
10   pear
11  other
12  other
13  other
14   pear

我们可以应用这样的功能。

df['data'] = df['data'].apply(lambda x : 'other' if len(df[df.data==x])<4 else x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM