DennisLi
DennisLi

Reputation: 4156

pandas convert all float columns into int

There are several float columns, I want to convert all of float columns into int.

prior to knowing the column names of those float columns, How do I convert all of them into int type in one line?

Upvotes: 7

Views: 9121

Answers (2)

anky
anky

Reputation: 75080

You can select_dtypes first and round them and finally convert to Int64 using df.astype which supports Nullable Int dtype:

m = df.select_dtypes(np.number)
df[m.columns]= m.round().astype('Int64')

Upvotes: 11

YOLO
YOLO

Reputation: 21709

You could use a simple for loop for this:

# say df is the dataframe
for c in df.columns:
    if df[c].dtype == np.float:
        df[c] = df[c].astype(int)

Upvotes: 5

Related Questions