Bird
0
0

Given a NumPy array of byte strings:

hard📝 Application Q9 of 15
NumPy - Array Data Types
Given a NumPy array of byte strings:
arr = np.array([b'abc', b'defg', b'hi'], dtype='S4')

How can you convert it to an array of Unicode strings without losing data?
Aarr.astype('U')
Barr.astype('S')
Carr.astype('U3')
Darr.astype('O')
Step-by-Step Solution
Solution:
  1. Step 1: Understand byte to Unicode conversion

    To convert byte strings to Unicode strings, use astype with dtype='U'.
  2. Step 2: Avoid fixed length truncation

    Using 'U' without length lets NumPy choose sufficient length to avoid data loss.
  3. Final Answer:

    arr.astype('U') -> Option A
  4. Quick Check:

    Use astype('U') to convert bytes to Unicode safely [OK]
Quick Trick: astype('U') converts byte strings to Unicode without truncation [OK]
Common Mistakes:
  • Using astype('U3') which truncates longer strings
  • Using astype('S') which keeps byte strings
  • Using astype('O') which creates object array

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes