Search code examples
pythonpandasconcatenationpandas-loc

Concatenating Zero to every row that has len() == 1.0 using loc[] methd


I have a set of data with one column:

  New_Value
0   51
1   45
2    1
3   78
4    0
5   78

csv files do not represent the zero found after a digit. 10 becomes 1 and this presents inaccuracy in what I'm trying to do. I want to add a zero to every row that has one digit and leave those that has two digits as they are. I have tried the following code but still get this error: AttributeError: 'str' object has no attribute 'str'.

    import pandas as pd

    df = pd.read_csv('Hellow world')

    for index in df.index:
        if df.loc[index,'New_Value'].str.len()== 1.0:
           df['New_Value']= data['New_Value'].str.cat(0)
           
         else if df.loc[index,'New_Value'].str.len()== 2.0:
           df.loc[index,'New_Value']

Solution

  • Try this:

    df['New_Value']=df.New_Value.apply(lambda x: str(x) + '0' if len(str(x))==1 else x)
    

    If you want the result to be integer, do this instead:

    df['New_Value']=df.New_Value.apply(lambda x: int(str(x) + '0') if len(str(x))==1 else x)