首页 > 解决方案 > 在二维数组中查找字符串并将它们转换为浮点数 [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填充)。

标签: python

解决方案


推荐阅读