pandas中DataFrame的“索引列”,删除pandas中的列

这篇博客讨论了在Pandas中如何删除DataFrame的索引列。通常,`del`和`drop`函数用于删除列,但它们不适用于索引列。如果索引列具有实际意义,首先需要取消其索引属性,然后可以使用`del`或`drop`删除。例如,通过设置`index_col=False`读取CSV文件,再使用`drop`函数删除列。
摘要由CSDN通过智能技术生成

关于DataFrame中的“索引列”

在DataFrame中的索引都在最左边的一列中,暂且叫它“索引列”,但其实它不是一个列,所以适用于删除列的命令都不适合它

删除列

方法一:del df[‘index’]

score=pd.read_csv('./dietplan.txt',sep='\t',index_col='Participant')
score

在这里插入图片描述

score=pd.read_csv('./dietplan.txt',sep='\t',index_col='Participant')
del score['Diet-Plan1']
score

在这里插入图片描述
但如果想用del删除设定为索引的那一列,就会报错:

score=pd.read_csv('./dietplan.txt',sep='\t',index_col='Participant')
del score['Participant']
score

在这里插入图片描述

方法二:df.drop([‘index’],axis = 1)

score=pd.read_csv('./dietplan.txt',sep='\t',index_col='Participant')
score=score.drop(['Diet-Plan1'],axis=1)
score

在这里插入图片描述
如果想用drop方法删除设定为索引的那一列,也会报错:

score=pd.read_csv('./dietplan.txt',sep='\t',index_col='Participant')
score=score.drop(['Participant'],axis=1)
score

在这里插入图片描述

删除“索引列”

如果DataFrame中的“索引列”是一个有实际意义的属性,例如:
在这里插入图片描述
这个表中的“Rank”是索引,但是同时它也代表了这些学校的2018的QS排名。

如果需要删除这一列,那么则需要去除这一列的索引属性,就是不把这一列设为索引。

qs = pd.read_excel('./2018-QS-World-University-Rankings-Top200.xlsx',index=False)

然后再用上面的两种方法进行删除

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值