[英]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.map
與Series.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.