代码可以在spyder(Python3,7)中使用,但不能在Jupyter笔记本中使用 以下代码在spyder中工作 在Jupyter笔记本中,我得到一个错误

代码可以在spyder(Python3,7)中使用,但不能在Jupyter笔记本中使用 以下代码在spyder中工作 在Jupyter笔记本中,我得到一个错误,python,jupyter-notebook,Python,Jupyter Notebook,以下错误出现在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_n

以下错误出现在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
TypeErrorTraceback(最近一次调用上次)
在()
3价格_num=[]
4对于汽车中的行[‘价格’]:
---->5价格(编号=re.sub(“[^0-9]”,第行)
6价格数量追加(整数(价格数量))
7.
/子目录中的dataquest/system/env/python3/lib/python3.4/re.py(模式、repl、字符串、计数、标志)
177一个可调用函数,它传递了match对象并且必须返回
178要使用的替换字符串。”“”
-->179返回编译(模式、标志).sub(repl、字符串、计数)
180
181 def子网(模式、应答、字符串、计数=0、标志=0):
TypeError:应为字符串或缓冲区

我猜
不是字符串,而是一些特定的数据类型。您可以尝试这样做,避免完全使用正则表达式:

price\u num=[]
对于df['price']中的行:
尝试:
价格=整数(行)
除值错误外:
通过
其他:
price_no_nonnum=''.join(如果c.isdigit(),则c代表str(行)中的c)
price=int(price\u no\u nonnum)
价格\追加数量(价格)

Jupyter使用的是python3.4,但正如您所指出的,spyder使用的是python3.7,因此可能是python版本不兼容(re模块的某些更改)嗯,你确定数据帧的内容是相同的吗?是的,数据帧是相同的。有人能提供我应该在JupyterMy中进行的代码更改吗?我的目标是从'df'数据帧的'price'列中删除非数字字符,然后将数据类型更改为int。我尝试了代码,但得到了以下错误:TypeError:'int'objectis not iterable'price'是一个非空对象我不知道你的数据是什么样子。你想要的是所有的字符串吗?是一些整数、字符串和浮点数吗?有什么东西你不想添加到列表中吗?我编辑了我的原始帖子,试图接受一个整数,否则就从字符串中解析一个整数。如果你运行命令
x=int(“foo”)
,Python将引发一个
ValueError
,因为字符串的值不是转换为int的有效值。捕获特定错误总比执行简单的
尝试要好:…除了:…
,因为您可能会使无意中出现的错误静音。
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))
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