Select multiple columns in a Pandas DataFrame

PandasServer Side ProgrammingProgramming

To select multiple columns in a Pandas DataFrame, we can create new a DataFrame from the existing DataFrame

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Create a new DataFrame, df1, with selection of multiple columns.

  • Print the new DataFrame with multiple selected columns.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)

print "Input DataFrame is:\n", df

df1 = df[['x', 'y']]
print "After selecting multiple columns:\n", df1

Output

Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

After selecting multiple columns:
   x  y
0  5  4
1  2  1
2  1  5
3  9 10
raja
Published on 30-Aug-2021 09:19:32
Advertisements