0

Below I have code listed. I have data frame a which has many columns I am attempting to query a subset of two columns 'Rank' & 'Country' from data frame a into my new data frame. Why does this code not work?

df= a['Rank', 'Country']

If I use

df=a['Rank']

It works fine.

1

1 Answer 1

3

Need another []:

df= a[['Rank', 'Country']]

what is same as, but it is less typing:

df = a.loc[:, ['Rank', 'Country']]

Sample:

a = pd.DataFrame({'Rank':[1,2,3],
                   'Country':[4,5,6],
                   'C':[7,8,9]})

print (a)
   C  Country  Rank
0  7        4     1
1  8        5     2
2  9        6     3

df = a.loc[:, ['Rank', 'Country']]
print (df)
   Rank  Country
0     1        4
1     2        5
2     3        6

df = a[['Rank', 'Country']]
print (df)
   Rank  Country
0     1        4
1     2        5
2     3        6

You can also check docs:

You can pass a list of columns to [] to select columns in that order.

Also for select column to one column DataFrame use [] too:

df = a[['Rank']]
print (df)
   Rank
0     1
1     2
2     3

but for Series:

s = a['Rank']
print (s)
0    1
1    2
2    3
Name: Rank, dtype: int64
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.