0

I have a column of float values in a Pandas data frame like so:

df['nums'] = [100.0, 35000.00, 42639.25, 552.27]

And I want to convert whole number floats like 100.0 into integer data type. I know I can access the last two digits of the list using str(df['nums'][1])[-2:] which should print '.0'.

I tried something like:

for i, row in enumerate(df.itertuples(), 1):
    if str(row[0])[-2:] == '.0':
        row[0] = row[0].astype(int)
    else:
        continue

Of course, this doesn't work in the slightest. How can I iterate over this column in a way that it can convert every whole number float into an int while keeping non-whole number floats intact? df['nums'] would look like this:

df['nums'] = [100, 35000, 42639.25, 552.27].

Thanks!

zow
  • 21
  • 1
  • Why do you want to cast the floats and integers? There may be an easier way depending on what the end goal is. – Edeki Okoh Sep 15 '20 at 16:49
  • 1
    Because Series can only have a single dtype, the only way to do what you want is to have the column upcast to `object` as the `int` dtype cannot hold a float and you wont get `1` as a float... IMO this is not a good option so *why* is it imperative to have `100.0` stored as `100` and not the float `100.0`? – ALollz Sep 15 '20 at 16:52
  • 1
    @EdekiOkoh I have to work with concatenating these numbers to a string, and if the float decimal is 0 then the concatenation won't yield the result I need. It's very peculiar, but I need to have it this way. – zow Sep 15 '20 at 16:58
  • @EdekiOkoh your response was just what I needed. Thank you for your time. – zow Sep 15 '20 at 17:03

0 Answers0