Selecting multiple columns in a pandas dataframe

669    Asked by AnushaAcharya in Data Science , Asked on Apr 9, 2021

 I have data in different columns but I don't know how to extract it to save it in another variable.

index a b c

1 2 3 4

2 3 4 5

How do I select 'a', 'b' and save it into df1?

I tried

df1 = df['a':'b']

df1 = df.ix[:, 'a':'b']

None seem to work.

Answered by Anusha Acharya

In pandas, you can select multiple column pandas by their name, but the column name gets stored as a list of the list that means a dictionary. It means you should use [ [ ] ] to pass the selected name of columns. This method df[['a','b']] produces a copy.

For example:

  df1 = df[['a','b']]

You can also use ‘.iloc’ method to access the list by column name. It is efficient to access the column by the index number of a column name.

For example:

  df1 = df.iloc[:,0:2]

Hope this answer helps.



Your Answer

Interviews

Parent Categories