w3resource

Select specific columns in Pandas DataFrame


2. Select Specific Columns ('X' and 'Y')

Write a Pandas program to select only the 'X' and 'Y' columns from the DataFrame.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'X': [1, 6, 8, 3, 7],
    'Y': [5, 2, 9, 4, 1],
    'Z': [3, 8, 6, 2, 9]
})

# Select 'X' and 'Y' columns
result = df[['X', 'Y']]
print(result)

Output:

   X  Y
0  1  5
1  6  2
2  8  9
3  3  4
4  7  1

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Select columns 'X' and 'Y'.
  • Print the results.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to select only the 'X' and 'Y' columns from a DataFrame and display their summary statistics.
  • Write a Pandas program to create a new DataFrame containing only the columns 'X' and 'Y' and then plot these columns against each other.
  • Write a Pandas program to extract 'X' and 'Y' columns and rename them to 'Feature1' and 'Feature2'.
  • Write a Pandas program to select the 'X' and 'Y' columns, then filter rows where 'X' is non-null and 'Y' is greater than a threshold.

Go to:


PREV : Select Rows Based on Column 'A' Value.
NEXT : Set MultiIndex and Access Data.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.