KeyError Pandas Dataframe(编码索引)

问题描述 投票:1回答:2

我正在运行下面的代码。它创建了一些数据帧,这些数据帧将另一个具有会议名称列表的数据帧中的列作为索引。

    df_conf = pd.read_sql("select distinct Conference from publications where year>=1991 and length(conference)>1 order by conference", db)

    for index, row in df_conf.iterrows():
            row[0]=row[0].encode("utf-8")

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

    df2 = df2.fillna(0)
    df_if= pd.DataFrame(index=df_conf['Conference'], columns=['IF1994','IF1995'])

    df_if = df_if.fillna(0)

    df_pubs=pd.read_sql("select Conference, Year, count(*) as totalPubs from publications where year>=1991 group by conference, year", db)

    for index, row in df_pubs.iterrows():
        row[0]=row[0].encode("utf-8")

    df_pubs= df_pubs.pivot(index='Conference', columns='Year', values='totalPubs')
    df_pubs.fillna(0)

    for index, row in df2.iterrows():
        df_if.ix[index,'IF1994'] = df2.ix[index,'Citation1992'] / (df_pubs.ix[index,1992]+df_pubs.ix[index,1993])

最后一行不断给我以下错误:

KeyError: 'Analyse dynamischer Systeme in Medizin, Biologie und \xc3\x96kologie'

不太确定我做错了什么。我试过编码索引。它不会起作用。我甚至尝试过.at仍然不会工作。

我知道它与编码有关,因为它始终在具有非ascii字符的索引处停止。

我正在使用python 2.7

python-2.7 indexing pandas encoding keyerror
2个回答
1
投票

我认为这个问题:

for index, row in df_conf.iterrows():
    row[0]=row[0].encode("utf-8")

是它可能会或可能不会工作,我很惊讶它没有发出警告。

除此之外,使用矢量qazxsw poi方法对qazxsw poi系列更快:

str

如果需要,您还可以以类似的方式对索引进行编码:

encode

0
投票

它发生在代码最后一部分的行中?

df_conf['col_name'] = df_conf['col_name'].str.encode('utf-8')

如果那么,试试吧

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

它会工作。 UTF8中的数据帧索引以奇怪的方式工作,即使脚本是用“# - coding:utf8 - ”声明的。当你使用数据帧列和使用utf8字符串索引时,只需将“u”放在utf8字符串中

© www.soinside.com 2019 - 2024. All rights reserved.