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

I want to add a zero to those values of a coulmn in a dataframe with a specific condition

I have a dataframe in which I want to add a zero in front of the values of a column, if the value is smaller than 10.

First I convert the values from int to str and then I try to use the endswith-method but it doesnt work. Its probably a syntax error.

This is my code:

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

df.info () 

if ( not df[df['Minute (Visit)'].astype(str).str.endswith('0')]):
    df['Minute (Visit)'] = '0' + df['Minute (Visit)'].astype(str)

This is my output

And the error Message says:

The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

>Solution :

Here is the solution:

import pandas as pd
df = pd.DataFrame({'Minute (Visit)': [10, 0, 2, 5, 23, 150]})

# Solution
df['Minute (Visit)'] = df['Minute (Visit)'].astype(str).str.zfill(2)

output

  Minute (Visit)
0             10
1             00
2             02
3             05
4             23
5            150
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