close

How to translate “bytes” objects into literal strings in pandas Dataframe, Python3.x?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to translate “bytes” objects into literal strings in pandas Dataframe, Python3.x in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to translate “bytes” objects into literal strings in pandas Dataframe, Python3.x?

  1. How to translate “bytes” objects into literal strings in pandas Dataframe, Python3.x?

    You can use vectorised str.decode to decode byte strings into ordinary strings:
    df['COLUMN1'].str.decode("utf-8")

  2. translate “bytes” objects into literal strings in pandas Dataframe, Python3.x

    You can use vectorised str.decode to decode byte strings into ordinary strings:
    df['COLUMN1'].str.decode("utf-8")

Method 1

You can use vectorised str.decode to decode byte strings into ordinary strings:

df['COLUMN1'].str.decode("utf-8")

To do this for multiple columns you can select just the str columns:

str_df = df.select_dtypes([np.object])

convert all of them:

str_df = str_df.stack().str.decode('utf-8').unstack()

You can then swap out converted cols with the original df cols:

for col in str_df:
    df[col] = str_df[col]

Method 2

Combining the answers by @EdChum and @Yu Zhou, a simpler solution would be:

for col, dtype in df.dtypes.items():
    if dtype == np.object:  # Only process byte object columns.
        df[col] = df[col].apply(lambda x: x.decode("utf-8"))

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read