在2d数组中查找字符串并将其转换为浮点[Python]

2024-09-29 06:35:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我将包含数字数据的csv文件作为数据帧导入,然后将其转换为二维浮点数组[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来再次尝试将它们转换为float(或者至少弄清楚为什么它们没有被转换)。原始csv文件仅包含数字,如-1,56E-05或1,27E-06,以及空白案例(导入+转换时由浮点类型的nan填充)


Tags: 文件csvtheto数据datadatestring