Reputation: 824
I have a column which I want to convert to a string consisting of only 12 digits. For this, I use the below snippet:
# Convert the column to a 12 digit string
df['MY_COLUMN'] = pd.to_numeric(df['MY_COLUMN'], errors='coerce')
df['MY_COLUMN'] = df['MY_COLUMN'].astype(str).str.zfill(12).str.slice(0, 12)
However, my output looks something like this:
16072934175.0
16026886931.0
16089115785.0
16095735607.0
16086482684.0
How could I obtain the same thing but without the final .0?
Expected output:
016072934175
016026886931
016089115785
016095735607
016086482684
Upvotes: 1
Views: 35
Reputation: 9786
The main reason why you could not convert it because it is float even after using .astype(str)
, you can give it a try and check the type of the column after .astype(str)
. But zfill(12)
expects a str
type to work not a float
.
You can try this example:
df = pd.DataFrame(
{'c': ['160c','33','c44','99','dd'],
'd': [1]*5
}
)
df = df.loc[pd.to_numeric(df['c'], errors='coerce').notna()]
df['c'] = df['c'].astype('str').apply(lambda x: x.zfill(12))
#output
Upvotes: 1