Intro
pandas使用apply函数或者groupby函数返回多个值时,会出现返回多个索引的问题,介绍下解决方法
复现
import pandas as pd
import numpy as np
df = pd.DataFrame({"name": ['a', 'b', 'c'],
"sex": ['男', '女', '男'],
"age": [10, 11, 12],
"weight": [40, 42, 45]})
df
| name | sex | age | weight |
---|
0 | a | 男 | 10 | 40 |
---|
1 | b | 女 | 11 | 42 |
---|
2 | c | 男 | 12 | 45 |
---|
常规groupby方法
df.groupby('sex', as_index=True).apply(lambda x: pd.DataFrame(
{'max_age': [x.age.max()], 'max_weight': [x.weight.max()]}))
| | max_age | max_weight |
---|
sex | | | |
---|
女 | 0 | 11 | 42 |
---|
男 | 0 | 12 | 45 |
---|
df.groupby('sex', as_index=False).apply(lambda x: pd.DataFrame(
{'max_age': [x.age.max()], 'max_weight': [x.weight.max()]}))
| | max_age | max_weight |
---|
0 | 0 | 11 | 42 |
---|
1 | 0 | 12 | 45 |
---|
- as_index=True,MultiIndex
- as_index=False,sex的取值都没了
解法
return Series可破,同时能够保留分组列的值
df.groupby('sex', as_index=False).apply(lambda x: pd.Series(
{'max_age': x.age.max(), 'max_weight': x.weight.max()}))
| sex | max_age | max_weight |
---|
0 | 女 | 11 | 42 |
---|
1 | 男 | 12 | 45 |
---|
df.groupby('sex', as_index=True).apply(lambda x: pd.Series(
{'max_age': x.age.max(), 'max_weight': x.weight.max()}))
| max_age | max_weight |
---|
sex | | |
---|
女 | 11 | 42 |
---|
男 | 12 | 45 |
---|
Ref
[1] https://stackoverflow.com/questions/10751127/returning-multiple-values-from-pandas-apply-on-a-dataframe
2022-11-27 于南京市江宁区