无法从Pandas的列名中删除unicode字符

2024-05-19 00:00:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pandas数据框中读取了一个csv文件,并试图从列名中删除unicode字符,但没有成功。

fl.columns
Index([ u'time', u'contact', u'address'], dtype='object')

headers=[ 'time', 'contact', 'address']
fl=pandas.read_csv('file.csv',header=None,names=headers)

还是不行

fl.columns
Index([ u'time', u'contact', u'address'], dtype='object')

即使重命名也不起作用

fl.rename(columns=lambda x:x.replace(x,x.value.encode('ascii','ignore')),inplace=True)
fl.columns
Index([ u'time', u'contact', u'address'], dtype='object')

有谁能告诉我为什么会发生这种事以及如何解决?谢谢。


Tags: columns文件csv数据pandasindexobjecttime
3条回答

在构建ML管道时,我也遇到了类似的问题。我的功能列表有Unicode和名字。

特点

[u'Customer_id', u'Age',.....]

一种摆脱它的方法是使用str()函数。创建一个新列表,并对每个值应用str函数。

features_new= [str(x) for x in features]

现在features_new列表将没有任何Unicode字符。告诉我它是怎么工作的。

如果确实需要删除u(因为这只是一个显示问题),可以执行以下非常肮脏的技巧:

from pandas import compat

compat.PY3 = True

df.columns
Index(['time', 'contact', 'address'], dtype='object')

我今天有个问题,用了:df['var'] = df['var'].astype(str)

相关问题 更多 >

    热门问题