How to decode a numpy array of dtype=numpy.string_?

2024/11/11 20:23:06

I need to decode, with Python 3, a string that was encoded the following way:

>>> s = numpy.asarray(numpy.string_("hello\nworld"))
>>> s
array(b'hello\nworld', dtype='|S11')

I tried:

>>> str(s)
"b'hello\\nworld'">>> s.decode()
AttributeError                            Traceback (most recent call last)
<ipython-input-31-7f8dd6e0676b> in <module>()
----> 1 s.decode()AttributeError: 'numpy.ndarray' object has no attribute 'decode'>>> s[0].decode()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-34-fae1dad6938f> in <module>()
----> 1 s[0].decode()IndexError: 0-d arrays can't be indexed
Answer

Another option is the np.char collection of string operations.

In [255]: np.char.decode(s)
Out[255]: 
array('hello\nworld', dtype='<U11')

It accepts the encoding keyword if needed. But .astype is probably better if you don't need this.

This s is 0d (shape ()), so needs to be indexed with s[()].

In [268]: s[()]
Out[268]: b'hello\nworld'
In [269]: s[()].decode()
Out[269]: 'hello\nworld'

s.item() also works.

https://en.xdnf.cn/q/71941.html

Related Q&A

Cosine similarity of word2vec more than 1

I used a word2vec algorithm of spark to compute documents vector of a text. I then used the findSynonyms function of the model object to get synonyms of few words. I see something like this: w2vmodel.f…

Handling empty case with tuple filtering and unpacking

I have a situation with some parallel lists that need to be filtered based on the values in one of the lists. Sometimes I write something like this to filter them:lista = [1, 2, 3] listb = [7, 8, 9] f…

pip3 install pyautogui fails with error code 1 Mac OS

I tried installing the autogui python extension:pip3 install pyautoguiAnd this installation attempt results in the following error message:Collecting pyautoguiUsing cached PyAutoGUI-0.9.33.zipComplete …

BERT get sentence embedding

I am replicating code from this page. I have downloaded the BERT model to my local system and getting sentence embedding. I have around 500,000 sentences for which I need sentence embedding and it is t…

Python Subversion wrapper library

In Subversions documentation theres an example of using Subversion from Python#!/usr/bin/python import svn.fs, svn.core, svn.reposdef crawl_filesystem_dir(root, directory):"""Recursively…

How to convert a selenium webelement to string variable in python

from selenium import webdriver from time import sleep from selenium.common.exceptions import NoSuchAttributeException from selenium.common.exceptions import NoSuchElementException from selenium.webdriv…

Why are session methods unbound in sqlalchemy using sqlite?

Code replicating the error:from sqlalchemy import create_engine, Table, Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmakerBase = declarative…

Combining Tkinter and win32ui makes Python crash on exit

While building a basic app using the winapi with Python 2.7 (Im on Windows 8.1), I tried to add a small Tkinter gui to the program. The problem is, whenever I close the app window, Python crashes compl…

horizontal tree with graphviz_layout

in python, with networkx. I can plot a vertical tree with : g=nx.balanced_tree(2,4)pos = nx.graphviz_layout(g, prog=dot)nx.draw(g,pos,labels=b_all, node_size=500)plt.show()similar to [root]|| |nod…

Finding first n primes? [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:Fastest way to list all primes below N in python Although I already have written a function to find all primes under n (pr…