I applied Pandas groupby to a dataframe to get all available combinations of a few fields as follows:
list_of_fields = [field1, field2, field3, field4]
grouped = df.groupby(list_of_fields)
This works as expected and when I print the groups in grouped.groups
I get the right tuple combinations.
Now I need to use the groups in grouped
to create multiple dataframes with the rows that match the values for each of the groups (basically, splitting my original dataframe). However, I do not know how to do this. I have tried the following:
for key in grouped.groups.keys():
partial_df = grouped.get_group(key)
But this is giving me a key error. Is this because the keys are multiple fields? How could I make it work? Thanks in advance!
question from:
https://stackoverflow.com/questions/65867283/apply-get-group-when-groupby-used-multiple-columns 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…