使用Python从数据框中删除多列 [英] Dropping Multiple Columns from a data frame using Python

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

问题描述

我知道如何使用Python从数据框中删除列.但是对于我的问题,数据集非常庞大,我要删除的列被组合在一起,或者基本上在列标题轴上单独分布.有没有一种较短的方法可以用更少的代码行来切片或删除所有列,而不是像我所做的那样将其写出.我在这里完成此操作的方式可行,但我想提供一种更概述的方式.

I know how to drop columns from a data frame using Python. But for my problem the data set is vast, the columns I want to drop are grouped together or are basically singularly spread out across the column heading axis. Is there a shorter way to slice or drop all the columns with fewer lines of code rather than to write it out like how I have done. The way I have done it here works but I would like a more summarized way.

flight_data_copy_final是应将其存储在其中的变量.

The flight_data_copy_final is the variable in which it should be stored.

这是我的代码:

from IPython.display import display

flight_data_copy_version1 = flight_data_copy.drop(flight_data_copy.ix[:,"Year": "FlightDate"].columns, axis=1)
flight_data_copy_version2 = flight_data_copy_version1.drop("TailNum", axis=1)
flight_data_copy_version3 = flight_data_copy_version2.drop("OriginStateFips", axis=1)
flight_data_copy_version4 = flight_data_copy_version3.drop("DestStateFips", axis=1)
flight_data_copy_version5 = flight_data_copy_version4.drop("Diverted", axis=1)
flight_data_copy_version6 = flight_data_copy_version5.drop("Flights", axis=1)
flight_data_copy_final = flight_data_copy.drop(flight_data_copy_version6.ix[:,"FirstDepTime":].columns, axis=1)

print (display (flight_data_copy_final))

推荐答案

要同时删除pandas中的多列,可以指定列名称,如下所示.如果希望在同一数据帧中受更改影响的列,则需要选项inplace=True.否则将其删除.

To delete multiple columns at the same time in pandas, you could specify the column names as shown below. The option inplace=True is needed if one wants the change affected column in the same dataframe. Otherwise remove it.

flight_data_copy.drop(['TailNum', 'OriginStateFips', 
                'DestStateFips', 'Diverted'], axis=1, inplace=True)

来源: Python熊猫-在一个命令中从数据框中删除多个序列

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

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