使用 loc[] 方法将零连接到具有 length() == 1.0 的每一行

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

我有一组数据只有一列:

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

csv 文件不表示数字后的零。 10 变为 1,这表明我正在尝试做的事情不准确。我想在每一行有一个数字的行中加一个零,而有两个数字的行保持原样。我尝试了以下代码,但仍然出现此错误: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']

试试这个:

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

如果您希望结果为整数,请改为:

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

试试这个:

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

解法:
这应该可以解决您的目的:

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

输出:

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