26 Oct Select multiple columns in a Pandas DataFrame
In Python, easily select multiple columns in a Pandas DataFrame. You can select more than one column without using built-in functions. More than two columns can also be selected in a range. In this lesson, learn how to:
- Select two columns
- Select multiple columns in a range
Select two columns
To select two specific columns from a Pandas DataFrame, mention the column names. Do not mention the column names you don’t want to display:
1 2 3 |
dataFrame[['Rank', 'Marks']] |
Let us see an example of selecting two specific columns in a Pandas DataFrame:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import pandas as pd # Dataset data = { 'student': ["Amit", "John", "Jacob", "David", "Steve"], 'rank': [1, 4, 3, 5, 2], 'marks': [95, 70, 80, 60, 90] } dataFrame = pd.DataFrame(data) print("Student Records\n\n",dataFrame) print("\nSelecting only two columns:\n",dataFrame[['rank', 'marks']]) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Student Records student rank marks 0 Amit 1 95 1 John 4 70 2 Jacob 3 80 3 David 5 60 4 Steve 2 90 Selecting only two columns: rank marks 0 1 95 1 4 70 2 3 80 3 5 60 4 2 90 |
Select multiple columns in a range
In a Pandas DataFrame, to select more than one column in a range, mention the index numbers in a range separated by a colon. The following selects columns 3rd to 5th
1 2 3 |
dataFrame[dataFrame.columns[2:5]] |
Let us see an example to select multiple columns in a range. We have added two more columns to the above example for our input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import pandas as pd # Dataset data = { 'Id': ["S01", "S02", "S03", "S04", "S05"], 'Student': ["Amit", "John", "Jacob", "David", "Steve"], 'Roll': [101, 102, 103, 104, 105], 'Rank': [1, 4, 3, 5, 2], 'Marks': [95, 70, 80, 60, 90], 'Address': ["East", "North", "West", "South", "SouthWest"] } dataFrame = pd.DataFrame(data) print("Student Records\n", dataFrame) # 3rd to 5th columns are selected print("\nSelecting columns in a range:\n", dataFrame[dataFrame.columns[2:5]]) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Student Records Id Student Roll Rank Marks Address 0 S01 Amit 101 1 95 East 1 S02 John 102 4 70 North 2 S03 Jacob 103 3 80 West 3 S04 David 104 5 60 South 4 S05 Steve 105 2 90 SouthWest Selecting columns in a range: Roll Rank Marks 0 101 1 95 1 102 4 70 2 103 3 80 3 104 5 60 4 105 2 90 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments