Enter columns as parameters in DF

36 views Asked by At

I have a Pandas DataFrame called table, and I want to see some columns of it, like:

table[['col_A', 'col_B', 'col_C', 'col_D', 'col_E']]

However, I want that 'col_C', 'col_D', 'col_E' is stored in a variable called var, in order to see my results doing something like that:

table[['col_A', 'col_B', var]]

I don't know how to define my variable. I tried to set

var = 'col_C' + ', ' + 'col_D' + ', ' + 'col_E'

in order to concatenate strings, but it fails.

If it is just one column it works. I mean, doing var2 = 'col_C', then I can access my table doing

table[['col_A', 'col_B', var2]]
1

There are 1 answers

1
Barmar On

The index is a list of strings, so use list concatenation.

var = ['col_C', 'col_D', 'col_E']
table2 = table[['col_A', 'col_B'] + var]