1

I am getting syntax error with the .merge() Pandas function.

What am I doing wrong and how can I fix it?

Below is a snippet of my code;

df2 = df2.merge(df1[list('col1','col2'], on ='ABC')
0

5 Answers 5

1

You need to use a string formatting for that:

>>> for n in (9, 99, 999, 9999):
...     print(f"{n:0>4}")
... 
0009
0099
0999
9999
Sign up to request clarification or add additional context in comments.

Comments

1

str.zfill(x) will put x zeroes before any string

If you'd rather use string formatting, f'{str:0x}' also works.

P.S. Don't name your strings str as it overloads the str class

2 Comments

I think this is more Pythonic than string formatting, especially C-style formatting.
I consider this less readable. I do prefer the new string formatting style to the old 'C style'.
0

Using str.zfill(width):

The method zfill() pads string on the left with zeros to fill width.

width − This is final width of the string. This is the width which we would get after filling zeros.

id = [6, 77, 888, 9999]
print([str(x).zfill(4) for x in id])

OUTPUT:

['0006', '0077', '0888', '9999']

EDIT:

To convert the column values in a column using list-comprehension:

import pandas as pd

df = pd.DataFrame({'un-padded':[6, 77, 888, 9999]})
df['padded'] = [str(x).zfill(4) for x in df['un-padded']]
print(df)

OUTPUT:

   un-padded padded
0          6   0006
1         77   0077
2        888   0888
3       9999   9999

3 Comments

I have one column containing thousands of such ID and need to insert a new column using zfill(). How can I do that?
@Pradeep added an edit for it :)
This is my first python code so I might be asking too silly things. import csv with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') with open ('new_'+csvfile, 'w') as output: writer = csv.writer(output, delimiter =',') writer.writerow(next(reader) + ['New-column'] After this I need to use zfill to insert new values which are there in xyz column. Could you help me to do this?
0

You will have to treat it as a string value, as numeric values can't have leading zeros. To create a 0-padded string of length 4, you can do this:

v = 4
print("{:04d}".format(v))

or the older style:

v = 4
print("%04d" % v)

Result either way:

0004

Comments

0

String formatting is the answer.

print('%04d' % 4)
0004
print('%04d' % 43)
0043

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.