gpt4 book ai didi

python - 创建一个列出值的数据透视表

转载 作者:太空狗 更新时间:2023-10-29 20:16:27 26 4
gpt4 key购买 nike

我需要使用什么 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]

关于python - 创建一个列出值的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com