如果列的唯一计数大于某个值,则更改数据框中的值

Eis*_*sen 5 python pandas

IP Routing Banking
1  1        6
2  1        6
3  1        7
3  3        8
4  5        9
5  9        7
Run Code Online (Sandbox Code Playgroud)

对于每一列,如果相同的值出现 2 次或更多次,我想将其更改为“其他”。我怎样才能在 pandas python 中做到这一点?

预期输出:

IP       Routing      Banking
1        Other        Other
2        Other        Other
Other    Other        Other
Other    3            8
4        5            9
5        9            Other
Run Code Online (Sandbox Code Playgroud)

Vla*_*kow 5

df[df.transform(lambda col: col.duplicated(keep=False))] = 'Other'
Run Code Online (Sandbox Code Playgroud)

结果:

      IP Routing Banking
0      1   Other   Other
1      2   Other   Other
2  Other   Other   Other
3  Other       3       8
4      4       5       9
5      5       9   Other
Run Code Online (Sandbox Code Playgroud)

与上面的想法相同,没有 lambda 调用:

cond = df.transform(pd.Series.duplicated, keep=False)
df.mask(cond, 'Other')
Run Code Online (Sandbox Code Playgroud)

要使用任何阈值:

您可以设置值计数必须达到的任何阈值才能被替换 - 不仅仅是 2(使用此答案中的方法):

n = 3  # set this threshold
Run Code Online (Sandbox Code Playgroud)
def to_replace(ser, n):
    counts = ser.value_counts()
    return ser.isin(counts[counts >= n].index)

df.mask(df.transform(to_replace, n=n), 'Other')


   IP Routing  Banking
0   1   Other        6
1   2   Other        6
2   3   Other        7
3   3       3        8
4   4       5        9
5   5       9        7
Run Code Online (Sandbox Code Playgroud)