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')
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')
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
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
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
String formatting is the answer.
print('%04d' % 4)
0004
print('%04d' % 43)
0043
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