Selecting Specific Columns from DataFrame

Write a Pandas program to select the ‘name’ and ‘score’ columns from the following DataFrame.

Example 1:

Input: DataFrame with 'name' and 'score' columns 
Output: 'name' and 'score' columns of the DataFrame

Example 2:

Input: DataFrame with 'name' and 'score' columns 
Output: 'name' and 'score' columns of the DataFrame

Use pandas DataFrame function loc or iloc to select specific columns from the DataFrame.

import pandas as pd

def select_columns(df):
    return df[['name', 'score']]

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'score': [85, 90, 87, 91]})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', 'Stark', 'Rogers'], 'score': [88, 92, 95, 97]})

print(select_columns(df1))
print(select_columns(df2))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!