如何使用pandas从数据框中删除列? [英] How to delete a column from a data frame with pandas?

查看:1473
本文介绍了如何使用pandas从数据框中删除列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了我的数据

import pandas as pd
df = pd.read_csv('/path/file.tsv', header=0, delimiter='\t')
print df

并获得:

          id    text
0    361.273    text1...
1    374.350    text2...
2    374.350    text3...

如何删除 id 上面数据框中的列?我尝试了以下方法:

How can I delete the id column from the above data frame?. I tried the following:

import pandas as pd
df = pd.read_csv('/path/file.tsv', header=0, delimiter='\t')
print df.drop('id', 1)

但它引发了这个异常:

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


推荐答案

实际删除列

del df ['id'] df.drop('id' ,1)应该有效,如果传递的列完全匹配

del df['id'] or df.drop('id', 1) should have worked if the passed column matches exactly

但是,如果你不需要删除列那么你就可以选择感兴趣的列,如下所示:

However, if you don't need to delete the column then you can just select the column of interest like so:

In [54]:

df['text']
Out[54]:
0    text1
1    text2
2    textn
Name: text, dtype: object

如果您从未想过它,那么您将cols列表传递给 read_csv as一个参数 usecols

If you never wanted it in the first place then you pass a list of cols to read_csv as a param usecols:

In [53]:
import io
temp="""id    text
363.327    text1
366.356    text2
37782    textn"""
df = pd.read_csv(io.StringIO(temp), delimiter='\s+', usecols=['text'])
df
Out[53]:
    text
0  text1
1  text2
2  textn

关于你的错误,因为'id'不在您的列中,或者拼写不同或有空格。要查看此内容,请查看 print(df.columns.tolist())的输出,这将输出列的列表,并显示是否有任何前导/尾随空格。

Regarding your error it's because 'id' is not in your columns or that it's spelt differently or has whitespace. To check this look at the output from print(df.columns.tolist()) this will output a list of the columns and will show if you have any leading/trailing whitespace.

这篇关于如何使用pandas从数据框中删除列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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