Pandas Groupby: Extract Group Keys as a List
To extract group keys and convert them to a list, you can use the groups attribute to retrieve the group keys and then use the tolist() method to convert them to a list. Here's an example code:
import pandas as pd
# Create sample data
data = {
'Name': ['Tom', 'Nick', 'John', 'Tom', 'Nick'],
'Age': [20, 25, 30, 20, 25],
'City': ['New York', 'Paris', 'London', 'New York', 'Paris']
}
df = pd.DataFrame(data)
# Group by 'Name'
groups = df.groupby('Name')
# Extract group keys and convert to list
group_keys = groups.groups.keys()
group_keys_list = list(group_keys)
print(group_keys_list)
This will output: ['John', 'Nick', 'Tom']
原文地址: https://www.cveoy.top/t/topic/fOpA 著作权归作者所有。请勿转载和采集!