簡體   English   中英

有沒有辦法讓 np.where 跳過任何包含非數字的字符串?

[英]is there a way to have np.where skip any strings that contain non numerics?

我正在嘗試將 dataframe 中的列從百分比 int 轉換為分類。 使用 np.where 我可以將它存儲一次。 由於 int 被轉換為 str,任何進一步拆分數據的額外嘗試都會失敗。 我不知道如何跳過帶有無法轉換為整數的單詞的字符串。 雖然 (x).astype(int) 適用於“26”,但它會為“低”拋出一個基數為 10 的錯誤

我正在嘗試做的事情:

life_data = [10, 50, 95, 19, 89] (實際上是我正在導入的 csv 文件)

第一關有效; 所有數據都從 int 轉換為 str

life_data = np.where(life_data < 50, 'low', life_data)

print(life_data)

['low', '50', '95', 'low', '89']

下一次嘗試失敗,因為單詞 'low' 試圖轉換為 int,拋出 base 10 錯誤

life_data = np.where(50 >= life_data.astype(int) < 91, 'mid', life_data)

預期 output(但失敗) ['low', 'mid', '95', 'low', 'mid']

嘗試省略“低”真值錯誤時也會失敗。 我嘗試使用 a.any() 或 a.all() 並且似乎無法正確包裝它。

life_data = np.where(life_data.= low and 50 >= life_data,astype(int) < 91, 'mid', life_data)

預期 output(但失敗) ['low', 'mid', '95', 'low', 'mid']

如果您想避免數字解析過程中出現錯誤,請嘗試

pd.to_numeric(['low', 'mid', '95', 'low', 'mid'], errors='coerce')      

Output

[nan, nan, 95., nan, nan]

你會發現切割 function 很有用。

life_data = pd.Series([10, 50, 95, 19, 89])
pd.cut(life_data, right=False,
       bins=[0, 50, 91, np.inf],
       labels=['Low', 'Med', 'High'])

Output

0     Low
1     Med
2    High
3     Low
4     Med

在這里,這應該工作:

在使用 np.where() 之前,添加一個 if 語句,說明

if ![insert your string here].isnumeric():
        [insert handling code here]

暫無
暫無

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

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