I have a raw data set as .txt file as follows
ID SI_Number
1 0010
2 0005
I am pushing this data to postgresql using psycopg2. In the DB I am seeing the following
ID SI_Number
1 10.0
2 5.0
In order to get rid of unwanted decimal places, I am using the following piece of code.
df['SI_number'] = df['SI_number'].astype(str).str.replace(r'.0$','',regex=True)
With this in the DB, I am seeing
ID SI_Number
1 10
2 5
But I want to populate the exact value in the DB. Like below:
ID SI_Number
1 0010
2 0005
I have tried df['SI_Number'].astype(str)
but no result.
I am reading the .txt file with the following
df = pd.read_csv(f,usecols=col_lst,sep='|',engine='python',encoding='iso-8859-1',error_bad_lines=False, warn_bad_lines=True)
I am using Linux OS. Also while uploading I am converting everything to VARCHAR().
Am I missing out anything?
You can convert to int -> string and then apply a zfill()
(zero fill)
>>> df = pd.DataFrame({"A": [1.0, 2.0, 30.0]})
>>> df
A
0 1.0
1 2.0
2 30.0
>>> df["A"] = df["A"].astype(int).astype(str).apply(lambda x: x.zfill(4))
>>> df
A
0 0001
1 0002
2 0030
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments