如何删除DataFrame中除某些列以外的所有列?

编程入门 行业动态 更新时间:2024-10-27 10:22:41
本文介绍了如何删除DataFrame中除某些列以外的所有列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个看起来像这样的DataFrame:

Let's say I have a DataFrame that looks like this:

a b c d e f g 1 2 3 4 5 6 7 4 3 7 1 6 9 4 8 9 0 2 4 2 1

我该如何删除除a和b之外的每一列?

How would I go about deleting every column besides a and b?

这将导致:

a b 1 2 4 3 8 9

我想用一种简单的代码删除这些内容,即删除a和b之外的所有列,因为假设我们有1000列数据.

I would like a way to delete these using a simple line of code that says, delete all columns besides a and b, because let's say hypothetically I have 1000 columns of data.

谢谢.

推荐答案

In [48]: df.drop(df.columns.difference(['a','b']), 1, inplace=True) Out[48]: a b 0 1 2 1 4 3 2 8 9

或:

In [55]: df = df.loc[:, df.columns.intersection(['a','b'])] In [56]: df Out[56]: a b 0 1 2 1 4 3 2 8 9

PS请注意, 最惯用的熊猫方式已由@Wen提出:

PS please be aware that the most idiomatic Pandas way to do that was already proposed by @Wen:

df = df[['a','b']]

df = df.loc[:, ['a','b']]

更多推荐

如何删除DataFrame中除某些列以外的所有列?

本文发布于:2023-10-28 13:51:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536809.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DataFrame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!