How to Get First Column of Pandas DataFrame?

How to Get First Column of Pandas DataFrame?

To get the first column of a pandas DataFrame, you can use the iloc indexer. Here's how:

import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # Get the first column first_column = df.iloc[:, 0] print(first_column) 

This will output:

0 1 1 2 2 3 Name: A, dtype: int64 

If you want the first column as a DataFrame (rather than a Series):

first_column_df = df.iloc[:, [0]] print(first_column_df) 

This will output:

 A 0 1 1 2 2 3 

The key here is using the iloc indexer, where the first dimension indicates rows and the second dimension indicates columns. The : in the first dimension means "all rows", and the 0 in the second dimension specifies the first column.


More Tags

emv validate-request android-architecture-components ngrx-effects google-chrome-devtools hyper-v non-printing-characters zlib loss-function sap-iq

More Programming Guides

Other Guides

More Programming Examples