user872009
user872009

Reputation: 438

All columns rounding up except new column

I want to add this column to an already existing dataframe.

df['THRESHOLD'] = df['AVG_CNT'] * 3
cols = ['AVG_CNT', 'STD_DEV', 'THRESHOLD']
df[cols] = df[cols].round(1)
print (df)

I want to round the columns to a single significant figure. All the columns get rounded up except the new df['THRESHOLD'] column. Why is this so?

Results of df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 16 entries, 0 to 15
Data columns (total 4 columns):
AVG_CNT      16 non-null float64
ID           16 non-null int64
STD_DEV      16 non-null float64
THRESHOLD    16 non-null float64
dtypes: float64(3), int64(1)
memory usage: 640.0 bytes
None

Upvotes: 0

Views: 47

Answers (1)

Joe Ferndz
Joe Ferndz

Reputation: 8508

You can use round to do this.

You can do it in a few ways.

df = df.round({'AVG_CNT': 1, 'STD_DEV': 1, 'THRESHOLD': 1})

or like you did:

cols = ['AVG_CNT', 'STD_DEV', 'THRESHOLD']
df[cols] = df[cols].round(1)

or

df[['AVG_CNT', 'STD_DEV', 'THRESHOLD']] = df[['AVG_CNT', 'STD_DEV', 'THRESHOLD']].round(1)

or use apply and Series.round

df[['AVG_CNT', 'STD_DEV', 'THRESHOLD']] = df[['AVG_CNT', 'STD_DEV', 'THRESHOLD']].apply(lambda x: pd.Series.round(x, 1))

or

df[cols] = df[cols].apply(lambda x: pd.Series.round(x, 1))

Upvotes: 1

Related Questions