Search code examples
pythonpandasnumpydataframeeval

I have a question about Python the numerical computation of letters


df = pd.DataFrame({'num':['9','','3','7','11']})
col_nm = 'num'
print(df)

  num
0   9
1    
2   3
3   7
4  11

If the num is greater than 5, I will convert it to 5. But after the number 10, there is no conversion.

string ="np.where(num == '',num,np.where(num >= '5', '5', num))"
string = string.replace(col_nm,"df['"+col_nm+"']")
df[col_nm] = eval(string)
print(df)

  num
0   5
1    
2   3
3   5
4  11

Is there any way to solve the logics using data and string while keeping them intact?


Solution

  • We need first convert to_numeric then use condition assign

    df['num'] = pd.to_numeric(df['num'],errors='coerce')
    df.loc[df['num'].between(5,10),'num'] = 5
    df
    Out[97]: 
        num
    0   5.0
    1   NaN
    2   3.0
    3   5.0
    4  11.0