Python条件聚合
我有一个大于3000个类别标签的大数据框。我想根据groupby计数有选择地重新编码标签。这就像Excel中的条件替换。例如:Python条件聚合,python,pandas,dataframe,conditional,aggregation,Python,Pandas,Dataframe,Conditional,Aggregation,我有一个大于3000个类别标签的大数据框。我想根据groupby计数有选择地重新编码标签。这就像Excel中的条件替换。例如: ID Label 1 cat 2 dog 3 cat 4 cat 5 dog 6 bird 每一个的计数: cat: 3 dog: 2 bird: 1 cat: 3 other: 3 逻辑:如果计数此代码使用pd.DataFrame.where()而不是np.where(),并在一行中执行: df.La
ID Label
1 cat
2 dog
3 cat
4 cat
5 dog
6 bird
每一个的计数:
cat: 3
dog: 2
bird: 1
cat: 3
other: 3
逻辑:如果计数此代码使用
pd.DataFrame.where()
而不是np.where()
,并在一行中执行:
df.Label = df.Label.where(df.groupby('Label')['Label'].transform('count') > 2, 'other')
print(df)
熊猫是数据帧吗?是的。这些都是用熊猫做的。很抱歉上面的格式错误,让我尝试修复它。
df['Label'] = df.groupby('Label')['Label'].transform('count')
df['New_Label'] = np.where(df.label <= 2, 'other', df.label)
df.Label = df.Label.where(df.groupby('Label')['Label'].transform('count') > 2, 'other')
print(df)
Label
ID
1 cat
2 other
3 cat
4 cat
5 other
6 other