python 3.x - Pandas use variable for column names part 2 -


given following data frame:

import pandas pd import numpy np df = pd.dataframe({'a':[1,2,3],                    'b':[4,5,6],                    'c':[7,8,9],                    'd':[1,3,5],                    'e':[5,3,6],                    'f':[7,4,3]})  df        b   c   d   e   f 0   1   4   7   1   5   7 1   2   5   8   3   3   4 2   3   6   9   5   6   3 

how can 1 assign column names variables use in referring said column names?

for example, if this:

cols=['a','b'] cols2=['c','d'] 

i want this:

df[cols,'f',cols2] 

but result this:

typeerror: unhashable type: 'list' 

i think need add column f list:

allcols = cols + ['f'] + cols2 print df[allcols]     b  f  c  d 0  1  4  7  7  1 1  2  5  4  8  3 2  3  6  3  9  5 

or:

print df[cols + ['f'] +cols2]     b  f  c  d 0  1  4  7  7  1 1  2  5  4  8  3 2  3  6  3  9  5 

Comments