将dtype <u30的numpy ndarray转换为=“” float

时间:2018-09-11 16:12:46

标签: python arrays string pandas numpy

=“”

我正在从熊猫数据帧单元中读取列表。

>>from pandas import DataFrame as table
>>x = table.loc[table['person'] == int(123), table.columns != 'xyz']['segment'][0]
>>print("X = ",x)

其中'person'和'segment'是我的列名,并且segment包含具有浮动值的列表。

>>X = [[39.414, 39.498000000000005]]

现在,当我尝试将其转换为numpy数组时,

>>x = numpy.asarray(x)
>>x=x.astype(float)

我收到以下错误

ValueError: could not convert string to float: '[[39.414, 39.498000000000005]]'

我尝试解析该字符串,并尝试删除任何“ \ n”或“”或任何不必要的引号,但是它不起作用。然后我试图找到dtype

>>print("Dtype = ", x.dtype)
>>Dtype = <U30

我假设我们需要将U30 dtype转换为float,但是我不确定如何执行。我正在使用numpy版本1.15.0。

我要做的就是将上述列表解析为带有浮点值的列表。

1 个答案:

答案 0 :(得分:1)

对于您看到的特定格式,请考虑np.fromstring。使用字符串切片,您还可以删除未使用的尺寸:

x = '[[39.414, 39.498000000000005]]'

res = np.fromstring(x[2:-2], sep=',')

# array([ 39.414,  39.498])