gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
pandas dataframe remove column with key not in other dataframe
- User
pandas dataframe remove column with key not in other dataframe
- Assistant
You can remove a column from a Pandas DataFrame if its key is not present in another DataFrame using the
isin()function and boolean indexing.Here's an example:
pythonimport pandas as pd # Create the first DataFrame df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) # Create the second DataFrame with selected keys df2 = pd.DataFrame({'A': [1, 2, 3], 'C': [7, 8, 9]}) # Get the keys present in df2 selected_keys = df2.columns # Remove columns from df1 if key not in selected_keys df1 = df1[df1.columns.isin(selected_keys)] print(df1)Output:
codeA C 0 1 7 1 2 8 2 3 9In the example above,
selected_keysrepresents the keys present in . The boolean indexing checks for each column in whether its key is present in . The resulting boolean array is used to select only the columns that satisfy the condition, effectively removing the columns that are not present in .