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']

Pandas Groupby: Extract Group Keys as a List

原文地址: https://www.cveoy.top/t/topic/fOpA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录