Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all but the 3 last columns of a dataframe in Python [duplicate]

I want to select all but the 3 last columns of my dataframe.

I tried :

df.loc[:,-3]

But it does not work

Edit : title

like image 307
Vincent Avatar asked Dec 04 '18 08:12

Vincent


People also ask

How do I copy all columns except one in pandas?

To select all columns except one column in Pandas DataFrame, we can use df. loc[:, df. columns != <column name>].

How do you select all columns except the last one in python?

You can also acheive selecting all columns except one column by deleting the unwanted column using drop() method. Note that drop() is also used to drop rows from pandas DataFrame. In order to remove columns use axis=1 or columns param.

How do I exclude the last column in a DataFrame?

You can also use DataFrame. drop() method to delete the last n columns. Use axis=1 to specify the columns and inplace=True to apply the change on the existing DataFrame.


2 Answers

Select everything EXCEPT the last 3 columns, do this using iloc:

In [1639]: df
Out[1639]: 
   a  b  c  d  e
0  1  3  2  2  2
1  2  4  1  1  1

In [1640]: df.iloc[:,:-3]
Out[1640]: 
   a  b
0  1  3
1  2  4
like image 151
Mayank Porwal Avatar answered Sep 20 '22 22:09

Mayank Porwal


Use this df.columns being sliced, and putted into a df[...] bracket:

print(df[df.columns[:-3]])
like image 40
U12-Forward Avatar answered Sep 23 '22 22:09

U12-Forward