KeyError:"[[",“]]]都不在"[列]"中; pandas 蟒 [英] KeyError: "None of [['', '']] are in the [columns]" pandas python

查看:748
本文介绍了KeyError:"[[",“]]]都不在"[列]"中; pandas 蟒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数据框中切两列.

I would like to slice two columns in my data frame.

这是我执行此操作的代码:

import pandas as pd
df = pd.read_csv('source.txt',header=0)
cidf=df.loc[:,['vocab','sumCI']]
print(cidf)

这是数据示例:

ID  vocab   sumCI   sumnextCI   new_diff
450      statu    3.0        0.0       3.0
391     provid    4.0        1.0       3.0
382  prescript    3.0        0.0       3.0
300   lymphoma    2.0        0.0       2.0
405      renew    2.0        0.0       2.0

**首先我收到此错误:**

**Firstly I got this error: **

KeyError: "None of [['', '']] are in the [columns]"'

我尝试过的事情:

  • 我尝试在读取文件时将headerindex 0放在一起,
  • 我尝试使用以下代码重命名列:

  • I tried putting a header with index 0 while reading the file,
  • I tried to rename columns with this code:

df.rename(columns=df.iloc[0],inplace=True)

  • 我也尝试过:

  • I also tried this:

    df.columns = df.iloc[1]
    df=df.reindex(df.index.drop(0))
    

  • 也在此链接

    以上均未解决该问题.

    推荐答案

    在您发布的打印稿中,好像您有空格作为分隔符. pd.read_csv将使用,作为默认分隔符进行读取,因此您必须明确声明它:

    By the print you posted, it seems like you have whitespaces as delimiters. pd.read_csv will read using , as default separator, so you have to explicitly state it:

    pd.read_csv('source.txt',header=0, delim_whitespace=True)
    

    这篇关于KeyError:"[[",“]]]都不在"[列]"中; pandas 蟒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆