warrenfitzhenry
warrenfitzhenry

Reputation: 2299

Pandas round multiple columns with text

I have this df:

      A        B
0    13045.0   1.0
1    13056.0   15.0
2    Mobi      2.0
3    Mobi      3.0
4    15056.0   5.0
5    15068.0   1.0

I would to round the numeric values to 0, to end up with:

      A        B
0    13045   1
1    13056   15
2    Mobi    2
3    Mobi    3
4    15056   5
5    15068   1

I have tried df.round(0) and df['A'].round(0) to no avail. How does one ignore the text values when rounding a column?

Upvotes: 0

Views: 233

Answers (1)

jezrael
jezrael

Reputation: 862691

You can use to_numeric + fillna + astype to int for create int column and then replace with mask and notnull:

a = pd.to_numeric(df.A, errors='coerce')
df.A = df.A.mask(a.notnull(), a.fillna(0).astype(int))
print (df)
       A     B
0  13045   1.0
1  13056  15.0
2   Mobi   2.0
3   Mobi   3.0
4  15056   5.0
5  15068   1.0

Upvotes: 1

Related Questions