Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to suffice a Zero based on the count of values in pandas

I have a dataframe with a column year as below

Year
202
2021
2022
202
2019

I need to add "0" for all the column values which has "202"

how can I do it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected Output

 Year
 2020
 2021
 2022
 2020
 2019

Code so far:

df['Year_1'] = df['Year'].str.len()

>Solution :

You can multiple values by 10 for values less like 1000:

df.loc[df.Year.lt(1000), 'Year'] *= 10
print (df)
   Year
0  2020
1  2021
2  2022
3  2020
4  2019

If working with strings add 0 if strings has lengths 3:

df.Year = df.Year.astype(str)

df.loc[df['Year'].str.len().eq(3), 'Year'] += '0'
print (df)
   Year
0  2020
1  2021
2  2022
3  2020
4  2019
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading