如何为Pandas DataFrame中找到的所有唯一值设置相同的频率?

问题描述 投票:0回答:1

我有一个Pandas DataFrame,它有2列:一列用于类别(PROBLEM_TYPE),一列用于类别的描述。显然,每个类别的描述值计数都不同,但是由于我打算训练基于此DataFrame的模型,因此我试图为每个类别设置相同的值计数。这样,我的模型将更加准确。

DataFrame:

filtered_df.head()

    PROBLEM_TYPE    DESCRIPTION
0   problem_type1   blabla...
1   problem_type1   blablablabla...
2   problem_type3   bla...
3   problem_type7   blablabloblo...
4   problem_type2   blobloble...

这是我调用value_counts()函数时得到的:

filtered_df["PROBLEM_TYPE"].value_counts()

problem_type1            141887
problem_type2             21663
problem_type3             19349
problem_type4             15710
problem_type5              5229
problem_type6              5161
problem_type7              4682
problem_type8              3672
problem_type9              3296
problem_type10             3131
Name: PROBLEM_TYPE, dtype: int64

如您所见,这里有10种不同的问题类型(类别),并且每种都有不同的价值计数。我的问题是如何为所有问题类型设置相同的计数值。例如,每个问题类型在DataFrame中的最小值计数(为3131)。

换句话说,如何将每个类别的频率设置为相同,所以下次我运行value_counts()函数时,它将看起来像这样:

filtered_df["PROBLEM_TYPE"].value_counts()

problem_type1              3131
problem_type2              3131
problem_type3              3131
problem_type4              3131
problem_type5              3131
problem_type6              3131
problem_type7              3131
problem_type8              3131
problem_type9              3131
problem_type10             3131
Name: PROBLEM_TYPE, dtype: int64

提前感谢。

python pandas dataframe
1个回答
0
投票

显然您想创建一个统一分布。您可以随机sample来自不同组的相同数量的元素。

df.groupby('PROBLEM_TYPE', group_keys=False).apply(pd.DataFrame.sample, 3131)
© www.soinside.com 2019 - 2024. All rights reserved.