如何在 Pandas Dataframe Python3.x 中将“bytes”对象翻译成文字字符串?

新手上路,请多包涵

我有一个 Python3.x pandas DataFrame,其中某些列是表示为字节的字符串(如 Python2.x 中)

 import pandas as pd
df = pd.DataFrame(...)
df
       COLUMN1         ....
0      b'abcde'        ....
1      b'dog'          ....
2      b'cat1'         ....
3      b'bird1'        ....
4      b'elephant1'    ....

当我使用 df.COLUMN1 按列访问时,我看到 Name: COLUMN1, dtype: object

但是,如果我按元素访问,它是一个“字节”对象

df.COLUMN1.ix[0].dtype
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'dtype'

如何将这些转换为“常规”字符串?也就是说,我怎样才能摆脱这个 b'' 前缀?

原文由 ShanZhengYang 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

您可以使用矢量化 str.decode 将字节字符串解码为普通字符串:

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

要为多列执行此操作,您可以只选择 str 列:

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

转换所有这些:

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

然后,您可以将转换后的列替换为原始的 df 列:

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

原文由 EdChum 发布,翻译遵循 CC BY-SA 3.0 许可协议

我添加了一些列的问题,这些列要么充满了 str,要么在数据帧中混合了 str 和字节。解决了 @Christabella Irwanto 提供的解决方案的微小修改:( 我更喜欢 str.decode('utf-8') 正如@Mad Physicist 所建议的那样)

 for col, dtype in df.dtypes.items():
        if dtype == np.object:  # Only process object columns.
            # decode, or return original value if decode return Nan
            df[col] = df[col].str.decode('utf-8').fillna(df[col])

>>> df[col]
0        Element
1     b'Element'
2         b'165'
3            165
4             25
5             25

>>> df[col].str.decode('utf-8').fillna(df[col])
0     Element
1     Element
2         165
3         165
4          25
5          25
6          25

原文由 GentilsTo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题