blu*_*e13 9 python pivot-table pandas
使用数据透视表生成列表需要使用什么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
Run Code Online (Sandbox Code Playgroud)
输出
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
Run Code Online (Sandbox Code Playgroud)
期望的输出
Experiment
Test point
0 1, 4
1 2, 5
2 3
Run Code Online (Sandbox Code Playgroud)
Rom*_*kar 11
您可以将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]
Run Code Online (Sandbox Code Playgroud)
使用
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
Run Code Online (Sandbox Code Playgroud)
或者,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
Run Code Online (Sandbox Code Playgroud)
但是,如果你想要那么作为列表.
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]
Run Code Online (Sandbox Code Playgroud)
x.astype(str).str.cat(sep=', ') 类似于 ', '.join(x.astype(str))
| 归档时间: |
|
| 查看次数: |
1986 次 |
| 最近记录: |