You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

numpy.reshape()是否仅支持整数类型?float参数引发类型错误求助

numpy.reshape()报错:TypeError: 'float' object cannot be interpreted as an integer

用户代码

import numpy as np 
import pandas as pd 
file = open("C:\Temp_Python\FF\FF_New.txt","r") 
data = file.readlines() 
f = [] 
index = [] 
for i in range(1,np.size(data)): 
    t = data[i].split() 
    index.append(int(t[0])) 
    for j in range(1, 5): 
        k = float(t[j]) 
        f.append(k/100)

n = len(f) 
nm = n/4 
print(nm)

f1 = np.reshape(f, [nm,4])
ff = pd.DataFrame(f1, index=index, columns= ['mkt','smb','hml','rf'])

print (index)
print (f)

报错信息

runcell(0, 'C:/Users/ujjwa/data retrieve processing.py') 
19.0 
Traceback (most recent call last):

File C:\Program Files\Spyder\pkgs\spyder_kernels\py3compat.py:356 in compat_exec exec(code, globals, locals)

File c:\users\ujjwa\data retrieve processing.py:18 f1 = np.reshape(f, [nm,4])

File <array_function internals>:200 in reshape

File C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py:298 in reshape return _wrapfunc(a, 'reshape', newshape, order=order)

File C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py:54 in _wrapfunc return _wrapit(obj, method, *args, **kwds)

File C:\Program Files\Spyder\pkgs\numpy\core\fromnumeric.py:43 in _wrapit result = getattr(asarray(obj), method)(*args, **kwds)

TypeError: 'float' object cannot be interpreted as an integer

用户疑问

numpy.reshape()是否不支持float数据类型,仅能使用int类型?


解答

不是reshape不支持处理float类型的数据,而是你传入的形状参数里包含了float类型的数值。

看你的代码:

nm = n/4

在Python3中,/除法运算的结果永远是float类型——哪怕n能被4整除(比如你输出的nm是19.0),而numpy的reshape要求每个维度的大小必须是整数类型,所以才会抛出这个类型错误。

解决方法

只需要把nm转换成整数类型即可,有两种常用方式:

  1. 使用整数除法//,确保结果是int:
    nm = n // 4
    
  2. 显式将float转成int:
    nm = int(n/4)
    

修改后,np.reshape(f, [nm,4])的形状参数就都是整数,就能正常执行了。

额外优化建议

  • 导入语句分开写,提升可读性:import numpy as np和import pandas as pd各占一行(原代码写在同一行,语法合法但不符合规范)。
  • 使用with语句打开文件,自动管理文件资源,避免忘记关闭:
    with open("C:\Temp_Python\FF\FF_New.txt","r") as file:
        data = file.readlines()
    

内容的提问来源于stack exchange,提问作者Ujjwal Alok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 22:45:32