1

Given the following data frame:

import pandas as pd
import numpy as 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

    A   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 one assign column names to variables for use in referring to said column names?

For example, if I do this:

cols=['A','B']
cols2=['C','D']

I then want to do something like this:

df[cols,'F',cols2]

But the result is this:

TypeError: unhashable type: 'list'

3 Answers 3

2

I think you need add column F to list:

allcols = cols + ['F'] + cols2
print df[allcols]
   A  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]
   A  B  F  C  D
0  1  4  7  7  1
1  2  5  4  8  3
2  3  6  3  9  5
Sign up to request clarification or add additional context in comments.

Comments

1

Need give a list with columns for reference.

In [48]: df[cols+['F']+cols2]
Out[48]:
   A  B  F  C  D
0  1  4  7  7  1
1  2  5  4  8  3
2  3  6  3  9  5

and, consider using df.loc[:, cols+['F']+cols2], df.ix[:, cols+['F']+cols2] for slicing.

Comments

1

Python 3 solution:

In [154]: df[[*cols,'F',*cols2]]
Out[154]:
   A  B  F  C  D
0  1  4  7  7  1
1  2  5  4  8  3
2  3  6  3  9  5

1 Comment

Maybe typo? SyntaxError: invalid syntax or maybe my python 2.7?

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.