簡體   English   中英

代碼適用於 spyder (python 3,7) 但不適用於 Jupyter Notebook

[英]code works in spyder (python 3,7) but not in Jupyter Notebook

以下代碼適用於 spyder

import re

price_num = []
for row in df['price']:
    price_no_nonnum = re.sub('[^0-9]','', row) # this code line works in spyder
    price_num.append(int(price_no_nonnum))

在 Jupyter 筆記本中,我收到一個錯誤

import re

price_num = []
for row in df['price']:
    price_no_nonnum = re.sub('[^0-9]','', row) # this code line gives an error in  jupyter
    price_num.append(int(price_no_nonnum))

Jupyter 中出現以下錯誤

TypeErrorTraceback (most recent call last)
<ipython-input-13-b3f4fcbe9d89> in <module>()
      3 price_num = []
      4 for row in autos['price']:
----> 5    price_no_nonnum = re.sub("[^0-9]","", row)
      6    price_num.append(int(price_no_nonnum))
      7 

/dataquest/system/env/python3/lib/python3.4/re.py in sub(pattern, repl, string, count, flags)
    177     a callable, it's passed the match object and must return
    178     a replacement string to be used."""
--> 179     return _compile(pattern, flags).sub(repl, string, count)
    180 
    181 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or buffer

我的猜測是row不是字符串,而是一些 Pandas 特定的數據類型。 您可以嘗試這樣做並完全避免使用正則表達式:

price_num = []
for row in df['price']:
    try:
        price = int(row)
    except ValueError:
        pass
    else:
        price_no_nonnum = ''.join(c for c in str(row) if c.isdigit())
        price = int(price_no_nonnum)
    price_num.append(price)

暫無
暫無

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

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