0

I have Pandas DataFrame in Python like below:

col
-------
7.0
2.0
NaN
...

"col1" is in float data type but I would like to convert displaying of floar values in this column from for example 7.0 to 7. I can not simply change date type to int because I have also "NaN" values in col1.

So as a result I need something like below:

col
-------
7
2
NaN
...

How can I do that in Python Pandas ?

dingaro
  • 2,156
  • 9
  • 29
  • you actually can. Pandas introduces Nullable Integer Data Types which allows integers to coexist with NaNs. So you should be good with `.astype('Int32')` – Himanshu Poddar Jul 18 '22 at 14:54
  • 1
    Is [this](https://stackoverflow.com/questions/21287624/convert-pandas-column-containing-nans-to-dtype-int) your answer? – I'mahdi Jul 18 '22 at 14:58
  • Formats belong to *formatting* and *displaying* a dataframe, not how it is stored. I don't quite understand the question. Do you want to display the dataframe with a specific format? That can be done. Store data in a dataframe "with specific float precision"? (Can't be done.) – creanion Jul 18 '22 at 14:59

1 Answers1

0

You can use convert_dtypes to perform an automatic conversion:

df = df.convert_dtypes('col')

For all columns:

df = df.convert_dtypes()

output:

    col
0     7
1     2
2  <NA>

After conversion:

df.dtypes

col    Int64
dtype: object
mozway
  • 194,879
  • 13
  • 39
  • 75
  • What is ? if I try to do: df[df["col"] == ""] ot df[df["col"] == np.nan] I do not have any results ? :/ – dingaro Jul 18 '22 at 15:11
  • You should never use direct comparison with NAs, use `df[df["col"].isna()]`. NB. This is **not** a string, but the `pd.NA` object. – mozway Jul 18 '22 at 15:14
  • Ok thank you, I gave best answer! Could you return yo my previous question ? – dingaro Jul 18 '22 at 15:22