使用 Python 从数据框中删除多列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40389018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:28:51  来源:igfitidea点击:

Dropping Multiple Columns from a data frame using Python

pythonpandasdataframedata-manipulation

提问by Deepak M

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.

我知道如何使用 Python 从数据框中删除列。但是对于我的问题,数据集很大,我想删除的列组合在一起,或者基本上单独分布在列标题轴上。有没有更短的方法来用更少的代码行来切片或删除所有列,而不是像我所做的那样写出来。我在这里完成的方式有效,但我想要一种更概括的方式。

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

flight_data_copy_final 是应该存储它的变量。

Here's my code:

这是我的代码:

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))

回答by Prasanth Regupathy

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

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

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

Source: Python Pandas - Deleting multiple series from a data frame in one command

来源:Python Pandas - 在一个命令中从数据框中删除多个系列