使用透视表生成列表需要使用什么aggfunc?我试过用不太管用的str。
输入

import pandas as pd
data = {
    'Test point': [0, 1, 2, 0, 1],
    'Experiment': [1, 2, 3, 4, 5]
}
df = pd.DataFrame(data)
print df

pivot = pd.pivot_table(df, index=['Test point'], values=['Experiment'], aggfunc=len)
print pivot

pivot = pd.pivot_table(df, index=['Test point'], values=['Experiment'], aggfunc=str)
print pivot

输出
   Experiment  Test point
0           1           0
1           2           1
2           3           2
3           4           0
4           5           1
            Experiment
Test point
0                    2
1                    2
2                    1
                                                Experiment
Test point
0           0    1\n3    4\nName: Experiment, dtype: int64
1           1    2\n4    5\nName: Experiment, dtype: int64
2                   2    3\nName: Experiment, dtype: int64

期望输出
            Experiment
Test point
0           1, 4
1           2, 5
2           3

最佳答案

您可以将list本身用作函数:

>>> pd.pivot_table(df, index=['Test point'], values=['Experiment'], aggfunc=lambda x:list(x))
           Experiment
Test point
0              [1, 4]
1              [2, 5]
2                 [3]

10-06 06:28