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')
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Pradeep
  • 31
  • 3

5 Answers5

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
Netwave
  • 40,134
  • 6
  • 50
  • 93
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

Alec
  • 8,529
  • 8
  • 37
  • 63
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
CryptoFool
  • 21,719
  • 5
  • 26
  • 44
0

String formatting is the answer.

print('%04d' % 4)
0004
print('%04d' % 43)
0043
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
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
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • I have one column containing thousands of such ID and need to insert a new column using zfill(). How can I do that? – Pradeep Apr 22 '19 at 09:06
  • @Pradeep added an edit for it :) – DirtyBit Apr 22 '19 at 09:15
  • 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? – Pradeep Apr 22 '19 at 10:15