pandas :Dataframe.Drop-ValueError:轴中不包含标签['id'] [英] Pandas: Dataframe.Drop - ValueError: labels ['id'] not contained in axis

查看:87
本文介绍了 pandas :Dataframe.Drop-ValueError:轴中不包含标签['id']的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图从熊猫的DataFrame中删除一列.从文本文件创建的DataFrame.

Attempting to drop a column from a DataFrame in Pandas. DataFrame created from a text file.

import pandas as pd 
df = pd.read_csv('sample.txt')
df.drop(['a'], 1, inplace=True)

但是,这会产生以下错误:

However, this generates the following error:

ValueError: labels ['a'] not contained in axis      

这是sample.txt文件的副本:

a,b,c,d,e
1,2,3,4,5
2,3,4,5,6
3,4,5,6,7
4,5,6,7,8

谢谢.

推荐答案

因此,问题在于您的"sample.txt"文件实际上并未包含您要删除的数据.

So the issue is that your "sample.txt" file doesn't actually include the data you are trying to remove.

您的行

df.drop(['id'], 1, inplace=True) 

表示要获取您的DataFrame(包括示例文件中的数据),在第一行(轴1)中找到值为"id"的列,然后进行就地替换(修改现有对象,而不是创建一个缺少该列的新对象,这将返回None并仅修改现有对象.)

is attepmting to take your DataFrame (which includes the data from your sample file), find the column where the value is 'id' in the first row (axis 1) and do an inplace replace (modify the existing object rather than create a new object missing that column, this will return None and just modify the existing object.).

问题在于您的样本数据不包含标题等于"id"的列.

The issue is that your sample data doesn't include a column with a header equal to 'id'.

在当前示例文件中,您只能拖放到轴1上的值为"a","b","c","d"或"e"的位置.请更正您的代码以删除这些值之一,或者获取具有正确标题的示例文件.

In your current sample file, you can only to a drop where the value in axis 1 is 'a', 'b', 'c', 'd', or 'e'. Either correct your code to drop one of those values or get a sample files with the correct header.

有关Pandas的文档并不完美,但以下是如何在Pandas中删除列的一个很好的示例:

The documentation for Pandas isn't fantastic, but here is a good example of how to do a column drop in Pandas: http://chrisalbon.com/python/pandas_dropping_column_and_rows.html

**为回应@saar的回答评论,添加了以下内容

** Below added in response to Answer Comment from @saar

这是我的示例代码: Sample.txt:

Here is my example code: Sample.txt:

a,b,c,d,e
1,2,3,4,5
2,3,4,5,6
3,4,5,6,7
4,5,6,7,8

示例代码:

import pandas as pd

df = pd.read_csv('sample.txt')
print('Current DataFrame:')
print(df)
df.drop(['a'], 1, inplace=True)
print('\nModified DataFrame:')
print(df)

输出:

>>python panda_test.py
Current DataFrame:
   a  b  c  d  e
0  1  2  3  4  5
1  2  3  4  5  6
2  3  4  5  6  7
3  4  5  6  7  8

Modified DataFrame:
   b  c  d  e
0  2  3  4  5
1  3  4  5  6
2  4  5  6  7
3  5  6  7  8

这篇关于 pandas :Dataframe.Drop-ValueError:轴中不包含标签['id']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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