使用数据透视表生成列表需要使用什么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
答案 0 :(得分:8)
使用
In [1830]: pd.pivot_table(df, index=['Test point'], values=['Experiment'],
aggfunc=lambda x: ', '.join(x.astype(str)))
Out[1830]:
Experiment
Test point
0 1, 4
1 2, 5
2 3
或者,groupby
会这样做。
In [1831]: df.groupby('Test point').agg({
'Experiment': lambda x: x.astype(str).str.cat(sep=', ')})
Out[1831]:
Experiment
Test point
0 1, 4
1 2, 5
2 3
但是,如果您想要列表。
In [1861]: df.groupby('Test point').agg({'Experiment': lambda x: x.tolist()})
Out[1861]:
Experiment
Test point
0 [1, 4]
1 [2, 5]
2 [3]
x.astype(str).str.cat(sep=', ')
与', '.join(x.astype(str))
答案 1 :(得分: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]
答案 2 :(得分:1)
选项1
str
预转换+ groupby
+ apply
。
您可以预转换为字符串以简化groupby
调用。
df.assign(Experiment=df.Experiment.astype(str))\
.groupby('Test point').Experiment.apply(', '.join).to_frame('Experiment')
Experiment
Test point
0 1, 4
1 2, 5
2 3
对此的修改将涉及到位分配,速度(assign
返回副本并且速度较慢):
df.Experiment = df.Experiment.astype(str)
df.groupby('Test point').Experiment.apply(', '.join).to_frame('Experiment')
Experiment
Test point
0 1, 4
1 2, 5
2 3
还有修改原始数据帧的缺点。
<强>性能强>
# Zero's 1st solution
%%timeit
df.groupby('Test point').agg({'Experiment': lambda x: x.astype(str).str.cat(sep=', ')})
100 loops, best of 3: 3.72 ms per loop
# Zero's second solution
%%timeit
pd.pivot_table(df, index=['Test point'], values=['Experiment'],
aggfunc=lambda x: ', '.join(x.astype(str)))
100 loops, best of 3: 5.17 ms per loop
# proposed in this post
%%timeit -n 1
df.Experiment = df.Experiment.astype(str)
df.groupby('Test point').Experiment.apply(', '.join).to_frame('Experiment')
1 loop, best of 3: 2.02 ms per loop
请注意,.assign
方法只比这慢几毫秒。对于较大的数据帧,应该会看到更大的性能提升。
选项2
groupby
+ agg
:
agg
之后的类似操作:
df.assign(Experiment=df.Experiment.astype(str))\
.groupby('Test point').agg({'Experiment' : ', '.join})
Experiment
Test point
0 1, 4
1 2, 5
2 3
这就是上面的版本。
# proposed in this post
%%timeit -n 1
df.Experiment = df.Experiment.astype(str)
df.groupby('Test point').agg({'Experiment' : ', '.join})
1 loop, best of 3: 2.21 ms per loop
对于较大的数据框, agg
应该会看到速度提升超过apply
。