[英]I'm trying to convert columns of input data (of type Numpy Array) into different types (float and U30)
[英]Converting numpy ndarray with dtype <U30 into float
我正在從pandas dataframe cell讀取一個列表。
>>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轉換為浮點數,但我不知道該怎么做。 我正在使用numpy版本1.15.0。
我想要做的就是將上面的列表解析為具有浮點值的列表。
數據類型應該讓你失望。 U30
這里代表一個長度為30的unicode字符串(如果你鍵入len(x)
你會看到這個字符串。
你所擁有的是列表的字符串表示,而不是字符串/浮點數/等的列表。
你需要在這里使用ast
庫:
x = '[[39.414, 39.498000000000005]]'
x = ast.literal_eval(x)
np.array(x, dtype=float)
array([[39.414, 39.498]])
對於您看到的特定格式,請考慮np.fromstring
。 使用字符串切片,您還可以刪除未使用的維度:
x = '[[39.414, 39.498000000000005]]'
res = np.fromstring(x[2:-2], sep=',')
# array([ 39.414, 39.498])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.