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.
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())
Try list comprehension
df = df.set_index([c for c in df.columns if c != 'cus_name'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With