【发布时间】:2025-12-12 17:50:01
【问题描述】:
我正在运行以下 python 脚本:
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
result=stats.ttest_ind(list1,list2)
print result[1]
但是我得到了如下错误:
ValueError: could not convert string to float: id
我对此感到困惑。 当我在交互部分中仅对一行尝试此操作时,而不是使用脚本进行循环:
>>> from scipy import stats
>>> import numpy as np
>>> f=open('data2.txt','r').readlines()
>>> w=f[1].split()
>>> l1=w[1:8]
>>> l2=w[8:15]
>>> list1=[float(x) for x in l1]
>>> list1
[5.3209183842, 4.6422726719, 4.3788135547, 5.9299061614, 5.9331108706, 5.0287087832, 4.57...]
效果很好。
谁能解释一下这个? 谢谢。
【问题讨论】:
-
从
csv文件中读取类型为df = df[['p']].astype({'p': float})的数据帧时,可能会出现这种错误ValueError: could not convert string to float:。如果csv是用空格记录的,python 不会将空格字符识别为 nan。您需要使用df = df.replace(r'^\s*$', np.nan, regex=True)用 NaN 覆盖空单元格
标签: python string floating-point