簡體   English   中英

我有一個關於 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM