Tuesday 10 October 2023

How to Select Two or More Columns in Pandas DataFrame?

Following statement select the Name and City columns of a DataFrame.

two_columns = ['Name', 'City']
name_and_city = df[two_columns]

In the above example, as we are selecting more than one column, the type of the variable name_and_city is a DataFrame. You can confirm the same by executing the statement ‘type(name_and_city)’.

 

Find the below working application.

 

select_two_or_more_columns.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)
print(df)

print('\nSelect Name and City columns')
two_columns = ['Name', 'City']
name_and_city = df[two_columns]
print(name_and_city)

print('\ntype of name_and_city : ', type(name_and_city))

Output

       Name  Age       City
0   Krishna   34  Bangalore
1       Ram   25    Chennai
2      Joel   29  Hyderabad
3      Gopi   41  Hyderabad
4  Jitendra   52  Bangalore
5       Raj   23    Chennai

Select Name and City columns
       Name       City
0   Krishna  Bangalore
1       Ram    Chennai
2      Joel  Hyderabad
3      Gopi  Hyderabad
4  Jitendra  Bangalore
5       Raj    Chennai

type of name_and_city :  <class 'pandas.core.frame.DataFrame'>


Previous                                                 Next                                                 Home

No comments:

Post a Comment