python pandas select columns combining list and other column name

Question:

I have created a list with 2 column names of a data frame.

Now I want to use this list to select this 2 columns along with other columns.

I have for example a data frame with 5 columns: A, B, C, D, E

I create a list that references A and B:

lst = ['A','B']

Then when I try to print it adding C I get an error.

print(df[lst,'C'])

TypeError: ‘([‘A’, ‘B’], ‘C’)’ is an invalid key

Which is the correct way to select the columns in a list along with others?

thanks!

Asked By: Pau Andrés

||

Answers:

Need to pass that as list too;

df[lst+['C']]
Answered By: Sachin Kohli
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.