[英]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.如果 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
Is there any way to solve the logics using data and string while keeping them intact?有没有办法解决使用数据和字符串的逻辑,同时保持它们的完整性?
We need first convert to_numeric
then use condition assign我们需要先转换为
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.