简体   繁体   中英

How to take all columns except one column in Data Frame Python?

I have DataFrame with for example 24 columns and my question is how can I take all columns except for instance column number 17 ?

data[:,:] using this kind of syntax.

you can do this:

data.drop(columns=['a']) # for column name
data.drop(columns=data.columns[17]) # for column index

It returns a dataframe that you can use.

For more information: pandas drop

You can use np.r_ with df.iloc like below for position based indexing with slicing:

pos_of_col= 17
df.iloc[:,np.r_[range(pos_of_col-1),range(pos_of_col,len(df.columns))]]

Demo , dropping column at position 4 (column 3 since python indexing starts at 0)

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,20,(5,10))).add_prefix("col_")
print(df,'\n')

pos_of_col= 4
print(df.iloc[:,np.r_[range(pos_of_col-1),range(pos_of_col,len(df.columns))]])



   col_0  col_1  col_2  col_3  col_4  col_5  col_6  col_7  col_8  col_9
0     12     15      0      3      3      7      9     19     18      4
1      6     12      1      6      7     14     17      5     13      8
2      9     19     16     19      5     15     15      0     18      3
3     17     19     19     19     14      7      0      1      9      0
4     10      3     11     18      2      0      0      4      5      6 

   col_0  col_1  col_2  col_4  col_5  col_6  col_7  col_8  col_9
0     12     15      0      3      7      9     19     18      4
1      6     12      1      7     14     17      5     13      8
2      9     19     16      5     15     15      0     18      3
3     17     19     19     14      7      0      1      9      0
4     10      3     11      2      0      0      4      5      6

I think the easier way would be:

data.loc[:, data.columns != 'col_name']

or

data.loc[:, ~data.columns.isin(['col_name'])]

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