我有一个
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 "", line 1, in
AttributeError: 'bytes' object has no attribute 'dtype'
如何将这些转换为“常规”字符串?也就是说,我怎样才能摆脱这个b”前缀?
您可以使用vectorised
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()
然后,您可以将转换后的cols与原始df cols交换出来:
for col in str_df:
df[col] = str_df[col]