2

In connection with the question I asked here: https://stackoverflow.com/questions/56375651/add-zeros-to-string-in-pandas-column-depends-of-length I have a problem with str.zfill() method.

My example data (column of DF):

0002131
dsda2123
eew12341
wewqsws1'
123

Following @jezrael advice I fill each row to 12 char by str.zfill() method.

Code: df['SampleNumber'] = df['SampleNumber'].str.zfill(12)

Result file:

000000002131
0000dsda2123
0000eew12341
wewqsws1'
000000000123

So all work fine but I have a problem with names where I have a ' character. The method passes it, and in result series I got a unchanged name. What is the problem here? How can I deal with it? In the documentation of that method, I found nothing about a similar problem. And type(wewqsws1') it's str.

Can someone know how to fix it?

Expecting result:

000000002131
0000dsda2123
0000eew12341
000wewqsws1'
000000000123
martin
  • 1,145
  • 1
  • 7
  • 24

1 Answers1

1

You probably have empty space in the end try str.strip().str.zfill(12)

Ex:

import pandas as pd

df = pd.DataFrame({"SampleNumber": ['000000002131', '0000dsda2123', '0000eew12341', "wewqsws1'  ", '000000000123']})
df['SampleNumber'] = df['SampleNumber'].str.strip().str.zfill(12)
print(df)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Thanks, it's works. But weird is that in raw txt file I have `0000eew12341'` not `0000eew12341 '`. And in pandas dataframe too... so I don't know why it's working but it is. Thank U Rakesh – martin May 30 '19 at 12:31