Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting all columns in DataFrame.set_index except one

Tags:

python

pandas

As the title says, I'm trying to select all columns except one in DataFrame.set_index.

I tried the following way:

df = df.set_index(list(df.columns != 'cus_name'))

The cus_name Series is the one I want to exclude. The above code raise a KeyError: True.

The list(df.columns != 'cus_name') is a list of boolean values [True, True, False, True, True, True, True, True, True, True, True, True] and what I need is a list of columns names except the cus_name.

I know I could explicitly input the complete list of columns I want in the set_index method but I was wandering if there is a more efficient way to do this.

like image 450
glpsx Avatar asked Oct 16 '25 19:10

glpsx


2 Answers

You can use pd.Index.difference() here with sort=False if order is important:

df=df.set_index(df.columns.difference(['cus_name'],sort=False).tolist())
like image 195
anky Avatar answered Oct 19 '25 11:10

anky


Try list comprehension

df = df.set_index([c for c in df.columns if c != 'cus_name'])
like image 24
Josef Korbel Avatar answered Oct 19 '25 09:10

Josef Korbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!