pandas.DataFrame.pop()
The pop() method in Pandas removes a specified column from a DataFrame and returns it as a Series object.
Key points:
Modifies the original DataFrame: Unlike some other methods, pop() changes the DataFrame in-place by removing the specified column.
Returns a Series: The removed column is returned as a Pandas Series object.
Raises KeyError: If the specified column doesn't exist, a KeyError is raised.
Python
import pandas as pd
data = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data)
# Remove the column 'col2' and store it in a Series
popped_column = df.pop('col2')
print(df) # Output:
col1 col3
0 1 7
1 2 8
2 3 9
print(popped_column) # Output:
0 4
1 5
2 6
Important Note:
For removing multiple columns, it's generally more efficient to use the drop() method instead of multiple pop() calls.
No comments:
Post a Comment