4

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.

4 Answers 4

6

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())
Sign up to request clarification or add additional context in comments.

Comments

4

Try list comprehension

df = df.set_index([c for c in df.columns if c != 'cus_name'])

Comments

3

A cheeky way to achieve this with set operations:

df.set_index(list(set(df.columns) - {'cus_name'}))

Comments

1

Alternatively,

df = df.set_index(df.columns.drop('cus_name').tolist()))

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.