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

90 Views Asked by At

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']
3

There are 3 best solutions below

2
On BEST ANSWER

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)
0
On

Try this:

    import pandas as pd

    df = pd.read_csv('Hellow world')

    for index in df.index:
        if len(list(df.loc[index,'New_Value'])) == 1.0:
           df['New_Value']= data['New_Value].apply(lambda x: int(str(x) + '0'))
           
         elif len(list(df.loc[index,'New_Value']))== 2.0:
           df.loc[index,'New_Value']
0
On

Solution:
This should solve your purpose:

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

OUTPUT:

   New_Value
0         51
1         10
2         20
3         45
4         20
5         24