take the first x columns of a dataframe in python

To take the first x columns of a DataFrame in Python using pandas, you can use the indexing operator [] and specify the range of columns you want to keep.

Here's an example:

main.py
import pandas as pd

# Create a DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9], 'D': [10, 11, 12]}
df = pd.DataFrame(data)

# Select the first x columns, where x is an integer
x = 2
df_first_x = df.iloc[:, :x]

print(df_first_x)
247 chars
12 lines

This will output the DataFrame with only the first x columns:

main.py
   A  B
0  1  4
1  2  5
2  3  6
32 chars
5 lines

Note that the indexing in pandas starts from 0. So, iloc[:, :x] selects all rows (:) and the first x columns (:x) in the DataFrame df.

related categories

gistlibby LogSnag