Home > Mobile >  How to mapping all column to pandas directly
How to mapping all column to pandas directly

Time:03-30

Here's my data

Id   Column_1   Column_2  Column_3
1        64.7       73.8      53.2
2        94.7       79.8      43.2

The mapping rule, under 60 is 0, 60-80 is 1 80 - 100 is 2, so the result is

Id   Column_1   Column_2  Column_3
1           1          1         0
2           2          1         0

Regards

CodePudding user response:

Use cut for all columns without first:

f = lambda x: pd.cut(x, bins=[-np.inf, 60,80, 100], labels=[0,1,2])
df.iloc[:, 1:] = df.iloc[:, 1:].apply(f)
print (df)
   Id Column_1 Column_2 Column_3
0   1        1        1        0
1   2        2        1        0

Alternative solution for MultiIndex Series by reshape:

df = (pd.cut(df.set_index('Id').stack(),
              bins=[-np.inf, 60,80, 100], 
              labels=[0,1,2])
        .unstack())
print (df)
   Column_1 Column_2 Column_3
Id                           
1         1        1        0
2         2        1        0

Another alternative with numpy.select:

df1 = df.iloc[:, 1:]
m1 = df1.le(60)
m2 = df1.gt(60) & df1.le(80)
m3 = df1.gt(80) & df1.le(100)
df.iloc[:, 1:] = np.select([m1,m2, m3], [0,1,2])
  • Related