基于Top N值的Pandas中的Bucket多个列

2024-09-26 22:55:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想遍历多个dataframe列,寻找每个列中的前n个值。如果列中的值在前n个值中,则保留该值,否则将bucket保存在“other”中。另外,我还想从中创建新的列。在

但是,我不确定在这种情况下如何使用.apply,因为似乎我需要同时引用列和行。在

np.random.seed(0)
example_df = pd.DataFrame(np.random.randint(low=0, high=10, size=(15, 5)),columns=['a', 'b', 'c', 'd', 'e'])
cols_to_group = ['a','b','c']
top = 2

对于下面的示例,下面是我不确定如何执行的伪代码:

伪代码:

^{2}$

预期产量:

粗略的例子,其中top=2。在

    a   b   c   d   e   a_bucketed b_bucketed
0   4   6   4   3   1     4          6
1   8   8   1   5   7     8          8 
2   8   6   0   0   2     8          6
3   4   1   0   7   4     4          Other
4   7   8   7   7   7     Other      8

Tags: 代码dataframedfbucketexampletopnp情况
1条回答
网友
1楼 · 发布于 2024-09-26 22:55:30

有一种方法。但目前还没有对领带进行治疗。在

df['a_bucketed'] = np.where(df['a'].isin(df['a'].value_counts().index[:2]), df['a'], 'Other')
df['b_bucketed'] = np.where(df['b'].isin(df['b'].value_counts().index[:2]), df['b'], 'Other')

#     a  b  c  d  e a_bucketed b_bucketed
# 0   5  0  3  3  7      Other      Other
# 1   9  3  5  2  4          9          3
# 2   7  6  8  8  1      Other      Other
# 3   6  7  7  8  1      Other      Other
# 4   5  9  8  9  4      Other          9
# 5   3  0  3  5  0          3      Other
# 6   2  3  8  1  3      Other          3
# 7   3  3  7  0  1          3          3
# 8   9  9  0  4  7          9          9
# 9   3  2  7  2  0          3      Other
# 10  0  4  5  5  6      Other      Other
# 11  8  4  1  4  9      Other      Other
# 12  8  1  1  7  9      Other      Other
# 13  9  3  6  7  2          9          3
# 14  0  3  5  9  4      Other          3

相关问题 更多 >

    热门问题