Python 3.x Python-检查对象是否为字节对象
我有一个数据帧(使用pandas.read_SAS从SAS文件导入),其中一列有时是字节对象,而另一列只是字符串 i、 e 在我的代码中,当我使用Python 3.x Python-检查对象是否为字节对象,python-3.x,pandas,object,Python 3.x,Pandas,Object,我有一个数据帧(使用pandas.read_SAS从SAS文件导入),其中一列有时是字节对象,而另一列只是字符串 i、 e 在我的代码中,当我使用 df1.loc[:,'barcode']=df1['barcode'].str.decode('utf-8') df2.loc[:,'barcode']=df2['barcode'].str.decode('utf-8') 但当我使用 df1.loc[:,'barcode']=df1['barcode'].str.decode('utf-8')
df1.loc[:,'barcode']=df1['barcode'].str.decode('utf-8')
df2.loc[:,'barcode']=df2['barcode'].str.decode('utf-8')
但当我使用
df1.loc[:,'barcode']=df1['barcode'].str.decode('utf-8')
df2.loc[:,'barcode']=df2['barcode'].str.decode('utf-8')
我得到了一些价值观
有没有办法专门检查它是否是字节对象?不幸的是,这两种情况都可能发生
另一个解决方案是在导出数据帧时保持这种类型,而不进行解码和编码
df1.to_csv(test.csv,index=False,encoding='utf-8')
但是,首先,上面的操作不起作用,其次,我想我仍然需要检查是否需要编码。您可以通过应用类型和检查条件来使用where,这样就完成了解码的条件应用。i、 e 例如:
df = pd.DataFrame({'barcode':[b'346546',b'645542',b'486465',b'135455',15200,15200]})
df['barcode'] = df['barcode'].where(df['barcode'].apply(type) != bytes, df['barcode'].str.decode('utf-8'))
输出:
barcode
0 346546
1 645542
2 486465
3 135455
4 15200
5 15200
0错误
1错误
2错误
3错误
4正确
5对
名称:条形码,数据类型:bool
df。其中
取假值,并用新解码的字符串替换
您还可以使用np.where
,mask
,这与此操作的df.where
非常相似
0 False
1 False
2 False
3 False
4 True
5 True
Name: barcode, dtype: bool