2

I am trying to make a dynamic list and then combine it with a fixed string to select columns from a dataframe:

import pandas as pd

df = pd.DataFrame([], columns=['c1','c2','c3','c4'])

column_list= ['c2','c3']

df2 = df[['c1',column_list]]

but I get the following error:

TypeError: unhashable type: 'list'

I tried a dict as well but that is similar error.

1 Answer 1

2

In your code, pandas tries to find the column ['c1','c2','c3','c4'], which is not possible as only hashable objects can be column names. Even if this wasn't triggering an error (e.g. if you used tuples), this wouldn't give you what you want. You need a 1D list.

Use expansion:

df[['c1', *column_list]]

Or addition:

df[['c1']+column_list]

Output:

Empty DataFrame
Columns: [c1, c2, c3]
Index: []
Sign up to request clarification or add additional context in comments.

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.