Home > Software engineering >  How to round off range of Pandas dataframe columns based on a condition
How to round off range of Pandas dataframe columns based on a condition

Time:08-29

Iam new to python. Below is my dataframe , I want to round the colums COLB to COLE to 0 decimal if the columns are greater than 1 if not I want to assign value 1

Name   COLB   COLC  COLD  COLE
A       1.82   2.3   5.2   8.2
B       0.2    8     12.3  1.3

I am trying below.

for x in (df.iloc[:, 1:5]):
    if x>1:
        df = df.round(0)
    else:
        flex_vol_df[col] = 1
    

    

Below is the error. When I printed just x , I only get float columns. Not sure why the below errors pops. Kindly help! Thank you.

TypeError: '>' not supported between instances of 'str' and 'int'

CodePudding user response:

You can do it like this if the columns only have non-negative values

df.iloc[:,1:] = df.iloc[:,1:].aggregate(lambda x: x.round().replace(0., 1.))

If the columns can have negative values, then use

df.iloc[:,1:] = df.iloc[:,1:].aggregate(lambda x: np.maximum(x, 1.).round())

where np is numpy

Output

   Name COLB    COLC    COLD    COLE
0   A   2.0     2.0     5.0     8.0
1   B   1.0     8.0     12.0    1.0

CodePudding user response:

clip to a lower value of 1, round and update the DataFrame in place.

df.update(df.iloc[:,1:].clip(lower=1).round())

Output:

  Name  COLB  COLC  COLD  COLE
0    A   2.0   2.0   5.0   8.0
1    B   1.0   8.0  12.0   1.0
  • Related