I want to add a leading zero for all rows in a column. Here is what the column looks like:
| value |
|---|
| -1 |
| 9 |
| 10 |
| -2 |
Desired output:
| value |
|---|
| -01 |
| 09 |
| 10 |
| -02 |
I tried using zfill but it doesn’t take care of the negative values.
df['value'] = df['value'].astype(str).str.zfill(2)
>Solution :
Try the following :
import pandas as pd
data = {'value': [-1, 9, 10, -2]}
df = pd.DataFrame(data)
# Function to add leading zero
def custom_zfill(x):
if x < 0:
return '-' + str(abs(x)).zfill(2)
else:
return str(x).zfill(2)
df['value'] = df['value'].apply(custom_zfill)
print(df)
