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

Time:08-10

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:

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()

CodePudding user response:

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
  • Related