我有一个关于 Python 字母数值计算的问题
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
如果num大于5,我就转为5。
但是在数字10之后,没有转换。
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
有没有办法解决使用数据和字符串的逻辑,同时保持它们的完整性?
我们需要先转换to_numeric
然后使用条件赋值
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
df = pd.DataFrame({'num':['9','','3','7','11']})
col_nm = 'num'
print(df)
num
0 9
1
2 3
3 7
4 11
如果num大于5,我就转为5。 但是在数字10之后,没有转换。
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
有没有办法解决使用数据和字符串的逻辑,同时保持它们的完整性?
我们需要先转换to_numeric
然后使用条件赋值
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