简体   繁体   中英

What's the most efficient way to drop columns (from beginning and end) in pandas from a large dataframe?

I am trying to drop a number of columns from the beginning and end of the pandas dataframe.

My dataframe has 397 rows and 291 columns. I currently have this solution to remove the first 8 columns, but I also want to remove some at the end:

SMPS_Data = SMPS_Data.drop(SMPS_Data.columns[0:8], axis=1)

I know I could just repeat this step and remove the last few columns, but I was hoping there is a more direct way to approach this problem.

I tried using

SMPS_Data = SMPS_Data.drop(SMPS_Data.columns[0:8,278:291], axis=1)

but it doesn't work.

Also, it seems that the .drop method somehow slows down the console responsiveness, so maybe there's a cleaner way to do it?

You could use .drop() , if you want to remove your columns by their column names

drop_these = ['column_name1', 'column_name2', 'last_columns']
df = df.drop(columns=drop_these)

If you know you want to remove them by their location, you could use .iloc() :

df.iloc[:, 8:15]  # For columns 8-15
df.iloc[:, :-5]   # For all columns, except the last five
df.iloc[:. 2:-5]  # For all columns, except the first column, and the last five

See this documentation on indexing and slicing data with pandas, for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM