Ye Htet
Ye Htet

Reputation: 27

Updating data type of a column from for loop

I am trying to change data type of a column to integer first then string given that it is a float. I would like to update the data type of column from within a while loop.

The column has a mix of string and float data types.

if data_type == str:
            column = column.fillna('') # empty string for NaN values
            index = 0
            for i in column:
                if column == float:
                    column[i] = int(column[i]) 


            return column.astype(str)

Upvotes: 1

Views: 1288

Answers (2)

ALollz
ALollz

Reputation: 59579

If some strings have leading 0s that you need to preserve, strip the last .0

s = pd.Series(['12385', 85020.0, '28593', '000123'])
s.astype(str).str.replace('\.0$', '')

0     12385
1     85020
2     28593
3    000123
Name: col, dtype: object

This assumes your float values are less than 1e+16, else the replace won't work.

Upvotes: 0

Chris
Chris

Reputation: 29742

Use pandas.to_numeric:

import pandas as pd

s = pd.Series(['12385', 85020.0, '28593'])
s = pd.to_numeric(s, downcast='integer').astype(str)

Output of s:

0    12385
1    85020
2    28593
dtype: object

Upvotes: 1

Related Questions