python - 在二维数组中查找字符串并将它们转换为浮点数 [Python]
问题描述
我将包含数值数据的 csv 文件导入为 DataFrame,然后将其转换为二维浮点数组 [2678x256]。这是我所做的:
date = 20180710 # date of data acquisition [YYYYMMDD]
s = "{}_l2b.csv".format(date) # to find the csv file corresponding to the date
TWOb = pd.read_csv(s, sep=';', decimal=',') # csv data imported as DataFrame
for i in range(0,len(TWOb),1): #convert string to float
for j in range(1,len(TWOb[0]),1):
strg = str(TWOb[i,j])
res = strg.replace('.', '', 1).isdigit() #True if string only contains numerics
if res == True :
strg1= float(strg)
TWOb[i,j] = strg1
else: # if string is not numerical, then:
strg0 = 0.
TWOb[i,j] = strg0
print(TWOb)
输出是:
array([[-3.31e-06, 0.0, 3.39e-06, ..., nan, nan, 0.0],
[1.1800000000000001e-07, 0.0, 1.27e-06, ..., 0.0208, 0.0257,
0.0279],
[-2.37e-07, 0.0, 1.27e-06, ..., nan, nan, 0.0],
...,
[4.7299999999999996e-07, 0.0, -8.49e-07, ..., 0.0213, 0.0251,
0.0288],
[2.37e-07, 0.0, -2.97e-06, ..., 0.0198, 0.0251, 0.0274],
[0.0, 0.0, 1.27e-06, ..., nan, nan, 0.0]], dtype=object)
但是在某些部分,例如TWOb[32:34,17:20]
,我得到
array([[-5.489999999999999e-05, -3.570000000000001e-05, '-8,60E-05'],
[-5.489999999999999e-05, -9.05e-05, '-1,37E-05']], dtype=object)
使用字符串,而它应该将它们全部转换......我不知道为什么。我想找到每个 str 以尝试再次将它们转换为浮点数(或者至少弄清楚为什么它们一开始没有被转换)。原始csv文件只包含-1,56E-05或1,27E-06等数字,以及空白情况(导入+转换时用float类型的nan填充)。
解决方案
推荐阅读
- youtube-api - 为我不是所有者的 YouTube 频道创建 API 密钥
- odata - Skip & Top 参数不传递到后端
- python - 使用误差线图旋转 matplotlib 标记
- flutter - 在 PageView Flutter 中管理多个表单验证
- spring - Spring Data Elasticsearch - 查询的根级别是否支持内部命中?
- swift - 如何整体旋转UILabel
- python-3.x - 当您输入 input()=='True' 时会发生什么
- ruby-on-rails - 为什么 ruby 将 1 和 0 的字母数字字符串排序为二进制?
- python - ValueError: 0 列传递,传递的数据有 3 列
- java - 线程“主”java.lang.NoClassDefFoundError 中的异常:org/jsoup/Jsoup