我有一个 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''
前缀?
最佳答案
您可以使用向量化的 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]
关于python - 如何将 "bytes"对象转换为 pandas Dataframe,Python3.x 中的文字字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40389764/