简体   繁体   中英

Python - replace values in a pandas data frame column

How can I make the following replacements in a column of pandas data frame which has a datatype of int64?

-change 1 and 2 to 0

-change 3 and 4 to 1

-change 5, 6, 7 to 2

So that at the end I only have 3 levels for classification?

Assuming df is the name of your dataframe and column is the name of a variable holding your column name as a string, then:

fun = lambda data: 0 if data < 3 else 1 if data < 5 else 2

df[column] = df[column].apply(fun)

will transform the column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM