Reputation: 2219
I have a column that has values of length 5,6,8, or 9. The column should just have values of length 6 or 9. I need to add leading 0's if the value is of length 5 or 8.
There is another column which can identfy if the value should be 6 or 9 digits (indicator). An indicator value of 'Red' means 6 digits, and an indicator of 'Green' means 9 digits.
df['digits'] = df[df['indicator'] == 'red']['digits'].apply(lambda x: "{:006d}".format(x))
df['digits'] = df[df['indicator'] == 'green']['digits'].apply(lambda x: "{:009d}".format(x))
id indicator digits
0 red 54324
1 red 654345
2 green 533345678
3 green 56438594
expected result:
id indicator digits
0 red 054324 # 0 added to this value
1 red 654345
2 green 533345678
3 green 056438594 # 0 added to this value
I am getting an error of ValueError: Unknown format code 'd' for object of type 'float'
. Any ideas why? What did I miss?
Upvotes: 0
Views: 43
Reputation: 16404
The error message tells you the type of your digits
column is float
, you need to change it to int
.
Also, lambda x: "{:006d}".format(x)
is just "{:006d}".format
:
df['digits'] = df[df['indicator'] == 'red']['digits'].astype(int).apply("{:006d}".format)
Upvotes: 1