how to delete every second column in pandas dataframe in python

You can delete every second column in a pandas DataFrame using the following code snippet:

main.py
import pandas as pd

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

# drop every second column
df = df.drop(df.columns[::2], axis=1)
201 chars
8 lines

In this example, we create an example DataFrame with columns A, B, C, and D. The df.drop() method is used to remove every second column of the DataFrame, starting from the first column (index 0). The resulting DataFrame df will only contain columns B and D.

related categories

gistlibby LogSnag