如何自动分类Pandas数据帧中的数据?

2024-04-28 22:08:27 发布

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

我有一个超过1000行和200列的数据框,类似这样:

     my_data:
             ID,   f1,   f2, ..     ,f200   Target
             x1     3     0, ..     ,2      0
             x2     6     2, ..     ,1      1
             x3     5     4, ..     ,0      0
             x4     0     5, ..     ,18     1
             ..     .     ., ..     ,..     .
             xn     13    0, ..     ,4      0

首先,我想将这些特性(f1-f200)自动离散成四个组,分别为nolowmediumhigh,这样在它们的列中有零的id(例如,f2中的x1包含0,xn中相同)标签应为“否”,其余应分为低、中、高三类。你知道吗

我发现这个:

  pd.cut(my_data,3, labels=["low", "medium", "high"]) 

但是,这并不能解决问题。你知道吗?你知道吗


Tags: 数据idtargetdatamylowf2f1
2条回答

使用np.选择你知道吗

# Iterate over the Dataframe Columns i.e. f1-f200

    for col in df.columns:

        # Define your Condition
        conditions = [
            (df[col] == 0),
            (df[col] == 1),
            (df[col] == 2),
            (df[col] > 3)]

        # Values you want to map
        choices = ['no','Low', 'Medium', 'High']

        df[col] = np.select(conditions, choices, default='Any-value')

因此,您需要创建动态容器并迭代列来获得这个结果。这可以通过以下方式实现:

new_df = pd.DataFrame()
for name,value in df1.iteritems(): ##df1 is your dataframe
    bins = [-np.inf, 0,df1[name].min()+1,df1[name].mean(), df1[name].max()]
    new_df[name] = pd.cut(df1[name], bins=bins, include_lowest=False, labels=['no','low', 'mid', 'high'])

相关问题 更多 >