Python 类型错误中的列表推导式任何人都请回答

List Comprehension in Python Type Error Cany anyone answer please

提问人:Peddi Akhilesh 提问时间:10/31/2023 最后编辑:Andrej KeselyPeddi Akhilesh 更新时间:10/31/2023 访问量:50

问:

# given code

# Import the data file and have a look!
import pandas as pd
s = pd.read_csv("celsius.csv")
s.head()

def converter(x):
  return 1.8*x + 32

f = [converter(p) for p in s]  
TypeError                                 Traceback (most recent call last)
<ipython-input-16-e542ae5b13a4> in <cell line: 11>()
      9   return 1.8*x + 32
     10 
---> 11 f = [converter(p) for p in s]

1 frames
<ipython-input-16-e542ae5b13a4> in converter(x)
      7 
      8 def converter(x):
----> 9   return 1.8*x + 32
     10 
     11 f = [converter(p) for p in s]

TypeError: can't multiply sequence by non-int of type 'float'

谁能告诉我为什么它是错误的?

Python list 函数

评论

0赞 Maria K 10/31/2023
p可能不是你所期望的数字。是字符串吗?如果是这样 - 将其转换为数字类型,具体取决于您拥有的数据。int(p)float(p)
0赞 Klops 10/31/2023
粘贴 Celsius.csv 文件的一些行,我们可以解决
0赞 Barmar 10/31/2023
循环遍历数据帧时,是一行,而不是行中的值。您应该使用 s['columname']' 替换为 CSV 中列的实际名称。scolumnname
0赞 juanpa.arrivillaga 10/31/2023
@Barmar没有。当您循环访问 DataFrame 时,它会循环访问列名。从这个意义上说,它的行为类似于列名和列之间的映射
2赞 juanpa.arrivillaga 10/31/2023
如果你打算使用 pandas,无论如何都应该使用矢量化操作来完成此操作。但问题是,遍历数据帧会遍历列名。

答: 暂无答案