w3resource

Select specific columns in Pandas DataFrame

Pandas: Advanced Indexing and Slicing Exercise-2 with Solution

Select Specific Columns:

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.

Python-Pandas Code Editor:

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

Previous: Select rows with specific condition in Pandas DataFrame.
Next: Set MultiIndex and access data in Pandas DataFrame/

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/select-specific-columns-in-pandas-dataframe.php