Philipp
Philipp

Reputation: 4799

How to clip just one column of dataframe

I have a pandas dataframe comprised of 3 columns: from [datetime64], to [datetime64], value [float64]. I just want to clip the "value" column to a maxmimum value.

df = dfo.clip(upper=100)

fails with TypeError: Cannot compare type 'Timestamp' with type 'int'

How can I clip just on column of a dataframe?

Upvotes: 13

Views: 13691

Answers (3)

Josua Krause
Josua Krause

Reputation: 71

The other answers modify the original dataframe which is not what OP's example did.

The correct answer would be:

df = dfo.copy()
df["value"].clip(upper=100, inplace=True)

This cannot be done in one line unfortunately.

Upvotes: 0

Jeff Ellestad
Jeff Ellestad

Reputation: 61

You can also use inplace=True to avoid the assignment:

dfo['value'].clip(upper=100, inplace=True)

Upvotes: 6

jezrael
jezrael

Reputation: 862701

You can specify column:

dfo['value'] = dfo['value'].clip(upper=100)

If possible multiple columns:

cols = ['value', 'another col']
dfo[cols] = dfo[cols].clip(upper=100)

Or if need clip all numeric columns filter them by DataFrame.select_dtypes:

cols = df.select_dtypes(np.number).columns
dfo[cols] = dfo[cols].clip(upper=100)

Upvotes: 21

Related Questions