KeyError:“ [['', '']] 中没有 [['', '']] 在 [columns]” 熊猫 python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51976930/
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
KeyError: "None of [['', '']] are in the [columns]" pandas python
提问by sariii
I would like to slice two columns in my data frame.
我想在我的数据框中切片两列。
This is my code for doing this:
这是我执行此操作的代码:
import pandas as pd
df = pd.read_csv('source.txt',header=0)
cidf=df.loc[:,['vocab','sumCI']]
print(cidf)
This is a sample of data:
这是一个数据示例:
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]”'
What I have tried:
我尝试过的:
- I tried putting a
header
withindex 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))
Also tried comments in this link
- 我试着在阅读文件时放一个
header
withindex 0
, 我尝试使用以下代码重命名列:
df.rename(columns=df.iloc[0],inplace=True)
我也试过这个:
df.columns = df.iloc[1] df=df.reindex(df.index.drop(0))
还尝试在此链接中发表评论
None of the above resolved the issue.
以上都没有解决问题。
采纳答案by rafaelc
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
将使用,
作为默认分隔符读取,因此您必须明确说明它:
pd.read_csv('source.txt',header=0, delim_whitespace=True)
回答by sejpalsinh jadeja
simply write code to create a new CSV file and use a new file
只需编写代码即可创建新的 CSV 文件并使用新文件
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.read_csv('source.txt',header=0, delim_whitespace=True)
headers = ['ID','vocab','sumCI','sumnextCI','new_diff']
df.columns = headers
df.to_csv('newsource.txt')
回答by kaushik Tummalapali
You can try doing this:
你可以尝试这样做:
pd.read_csv('source.txt',header=0, delim_whitespace=True)
If you have any white spaces in the data you're will get an error, so delim_whitespace
is included to remove those in case they're in the data.
如果数据中有任何空格,您将收到错误消息,因此delim_whitespace
包含在内以删除它们,以防它们在数据中。