how do I remove all columns with all nan values in pandas?
- User
how do I remove all columns with all nan values in pandas?
Assistant
You can use the
dropna()method in pandas to remove columns with all NaN values. Here's an example:import pandas as pd # Create a sample DataFrame with some NaN values data = { 'A': [1, 2, None, 4], 'B': [None, None, None, None], 'C': [5, 6, 7, 8], } df = pd.DataFrame(data) # Remove all columns with all NaN values df = df.dropna(axis=1, how='all') # Print the modified DataFrame print(df)This will output:
A C 0 1 5 1 2 6 2 NaN 7 3 4 8The
axisparameter specifies whether to remove rows (axis=0) or columns (axis=1). Thehowparameter specifies whether to remove rows or columns that are all NaN (how='all') or contain at least one NaN value (how='any').
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.