2

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.

3
  • 3
    You can just use the drop() function to drop the 17th column, like so: df.drop('17_column', 1) Commented Sep 25, 2020 at 15:23
  • df.iloc[:, start_col:end_col] Commented Sep 25, 2020 at 15:23
  • Manakin, but using your code I only take start col for example 1 and end col for example 16, but I want all columns except number 17 Commented Sep 25, 2020 at 15:28

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, its way better than the previous edit which didnt work, I cant delete my answer now but this method is more readable.
I updated the response. drop([17]) was just deleting rows.
2

I think the easiest way would be:

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

or

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.