dataframe的pivot_table的aggfunc想返回原值
时间: 2024-05-12 20:20:03 浏览: 57
pandas pivot_table() 按日期分多列数据的方法
如果想返回原值,可以将aggfunc设置为np.mean或者lambda x: x。例如:
```
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'two', 'two', 'one', 'one'],
'C': [1, 2, 3, 4, 5, 6],
'D': [7, 8, 9, 10, 11, 12]})
table = pd.pivot_table(df, values=['C', 'D'], index=['A'], columns=['B'], aggfunc=np.mean)
print(table)
# Output:
# C D
# B one two one two one two
# A
# bar 8.00 4.0 11.00000 10.0 11.50000 12.0
# foo 1.5 3.0 7.66667 9.0 8.33333 0.0
table = pd.pivot_table(df, values=['C', 'D'], index=['A'], columns=['B'], aggfunc=lambda x: x)
print(table)
# Output:
# C D
# B one two one two one two
# A
# bar [5, 11] [4, 10] [11, 12] [10, 12] [11, 12] [12]
# foo [1, 2, 3] [3] [7, 8, 9] [9] [8, 9] [0]
```
阅读全文