how to filtera dataframe based on column name in python in python

To filter a dataframe based on column name in Python using pandas library, you can use the following code:

main.py
import pandas as pd

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

# filter dataframe by column name
filtered_df = df.filter(items=['A', 'C'])

print(filtered_df)
213 chars
10 lines

In this example, we create a dataframe df and filter it to only include columns 'A' and 'C' with filtered_df = df.filter(items=['A', 'C']). You can modify the list of column names in items to filter based on different columns. The resulting filtered dataframe is then printed to the console with print(filtered_df).

related categories

gistlibby LogSnag