0

What is the best method to convert a dataframe column (object) containing nan and floats 900.0 to nan and 900?

dirtyw0lf
  • 1,899
  • 5
  • 35
  • 63
  • 1
    Are you asking how to convert the column to integer or do you just want to print it as an integer. Read [this post](https://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping-array-type-as-integer-while-having-a-nan-value). – pault Jul 31 '18 at 16:03

1 Answers1

0

IIUC: Input:

    df = pd.DataFrame(['1.0','5.0',np.nan,'9.0', '100.0', np.nan, '500.0'], columns=['a'])

       a
0    1.0
1    5.0
2    NaN
3    9.0
4  100.0
5    NaN
6  500.0

Let's try this:

pd.to_numeric(df.a).fillna(0).astype(int).astype(str).mask(df.a.isnull())

Output:

0      1
1      5
2    NaN
3      9
4    100
5    NaN
6    500
Name: a, dtype: object
Scott Boston
  • 147,308
  • 15
  • 139
  • 187