sdom
sdom

Reputation: 319

Adding a zero to the end of the string value without changing the column type

I have string column in my df table, like this below:

d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']}
df = pd.DataFrame(data=d)
df

enter image description here

I would like to convert this column, so that all values ​​contain two decimal places, but without changing the type of this column to numeric type.

Expected output - a string column with values:

enter image description here

I am a little new to Python, I tried padding 0 How to pad a numeric string with zeros to the right in Python? depending on the length of the value in the column, but it actually didn't work.

Do you have idea how to handle it?

Upvotes: 0

Views: 460

Answers (4)

Ruggero
Ruggero

Reputation: 447

You can easily use the round or format function. In your specific case, using format, you can write something like this:

d = ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']
for i in range(len(d)):
     if d[i] == '':
          d[i] = '0'    
     d[i] = "{:.2f}".format(float(d[i]))
print ('col1', d)

output:

'col1', ['1.20', '3.40', '1.99', '0.14', '2.90', '0.00', '2.30']

Upvotes: 0

mozway
mozway

Reputation: 262164

Use str.ljust:

df['col1'] = df['col1'].str.ljust(4, '0')

output:

   col1
0  1.20
1  3.40
2  1.99
3  0.14
4  2.90
5  2.30

To leave empty rows intact:

df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0'))

output:

   col1
0  1.20
1  3.40
2  1.99
3  0.14
4  2.90
5      
6  2.30

NB. to get the max string length: df['col1'].str.len().max() -> 4

Upvotes: 2

Agent Biscutt
Agent Biscutt

Reputation: 737

This one will work no matter how many columns are in your dictionary. Try this:

d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9' '', '2.3']}
for x in d:
  for y in range(0,len(d[x])):
    d[x][y]=d[x][y].ljust(4,"0")
print(d)

Upvotes: 0

gtomer
gtomer

Reputation: 6574

Like this:

df['col1'] = df['col1'].astype(float).map('{:,.2f}'.format).astype(str)

If you have '' in this column you better replace them before to '0'.

Upvotes: 1

Related Questions