将包含整数值范围的字符串数组转换为浮点数数组
Converting an array of strings containing range of integer values into an array of floats
Click here to see an image that contains a screenshot sample of the data.
我有一个 CSV 文件,其中有一列温度范围,其值如“20-25”存储为字符串。我需要将其转换为浮点数 22.5。
需要对此类值的整列进行此操作,而不是单个值。我想知道如何在 Python 中完成此操作,因为我对它很陌生.
注意示例数据图像中记录中也有 NaN 值
如反应中所说,使用“-”作为参数拆分数组。
其次,创建一个浮点数组。最后,使用 numpy 取平均值。
import numpy as np
temp_input = ["20-25", "36-40", "10-11", "23-24"]
# split and convert to float
# [t.split("-") for t in temp_input] is an inline iterator
tmp = np.array([t.split("-") for t in temp_input], dtype=np.float32)
# average the tmp array
temp_output = np.average(tmp, axis=1)
这是一个单行本:
temp_output = [np.average(np.array(t.split('-'), dtype=np.float32)) for t in temp_input]
Click here to see an image that contains a screenshot sample of the data. 我有一个 CSV 文件,其中有一列温度范围,其值如“20-25”存储为字符串。我需要将其转换为浮点数 22.5。 需要对此类值的整列进行此操作,而不是单个值。我想知道如何在 Python 中完成此操作,因为我对它很陌生.
注意示例数据图像中记录中也有 NaN 值
如反应中所说,使用“-”作为参数拆分数组。 其次,创建一个浮点数组。最后,使用 numpy 取平均值。
import numpy as np
temp_input = ["20-25", "36-40", "10-11", "23-24"]
# split and convert to float
# [t.split("-") for t in temp_input] is an inline iterator
tmp = np.array([t.split("-") for t in temp_input], dtype=np.float32)
# average the tmp array
temp_output = np.average(tmp, axis=1)
这是一个单行本:
temp_output = [np.average(np.array(t.split('-'), dtype=np.float32)) for t in temp_input]