pandas 数据帧编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30156012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:39:49  来源:igfitidea点击:

Dataframe encoding

python-2.7pandasdataframe

提问by BKS

Is there a way to encode the index of my dataframe? I have a dataframe where the index is the name of international conferences.

有没有办法对我的数据帧的索引进行编码?我有一个数据框,其中索引是国际会议的名称。

df2= pd.DataFrame(index=df_conf['Conference'], columns=['Citation1991','Citation1992'])

df2= pd.DataFrame(index=df_conf['Conference'], columns=['Citation1991','Citation1992'])

I keep getting: KeyError: 'Leitf\xc3\xa4den der angewandten Informatik'

我不断得到: KeyError: 'Leitf\xc3\xa4den der angewandten Informatik'

whenever my code references a foreign conference name with unknown ascii letters.

每当我的代码引用具有未知 ascii 字母的外国会议名称时。

I tried:

我试过:

df.at[x.encode("utf-8"), 'col1']

df.at[x.encode('ascii', 'ignore'), 'col']

Is there a way around it? I tried to see if I could encode the dataframe itself when creating it, but it doesn't seem I can do that either.

有办法解决吗?我试图查看在创建数据帧时是否可以对其本身进行编码,但似乎我也无法做到。

回答by Guillaume Jacquenot

Setting up the encoding should be treated when reading the input file, using the option encoding

设置编码应该在读取输入文件时处理,使用选项 encoding

df = pd.read_csv('bibliography.csv', delimiter=',', encoding="utf-8")

or if the file uses BOM,

或者如果文件使用BOM,

df = pd.read_csv('bibliography.csv', delimiter=',', encoding="utf-8-sig")

回答by BKS

If you're not using csv, and you want to encode your string index, this is what worked for me:

如果您不使用 csv,并且想对字符串索引进行编码,那么这对我有用:

df.index = df.index.str.encode('utf-8')

回答by Marcel Kim

Just put "u" in front of utf8 strings such that

只需将“u”放在 utf8 字符串前面,这样

df2= pd.DataFrame(index=df_conf[u'Conference'], columns=[u'Citation1991',u'Citation1992'])

It will work.

它会起作用。