【发布时间】:2021-08-25 19:23:47
【问题描述】:
我有一个看起来像这样的熊猫数据框。
import pandas as pd
df = pd.DataFrame({
'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
'col2': ['test1', 'test1', 'test1', 'test1', 'test2', 'test2', 'test2',
'test2', 'test3', 'test3', 'test3', 'test3', 'test4', 'test5',
'test1', 'test1'],
'col3': ['t1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1',
't1', 't1', 't1', 't1', 't1'],
'col4': ['input1', 'input2', 'input3', 'input4', 'input1', 'input2',
'input3', 'input4', 'input1', 'input2', 'input3', 'input5',
'input2', 'input6', 'input1', 'input1'],
'col5': ['result1', 'result2', 'result3', 'result4', 'result1', 'result2',
'result3', 'result4', 'result1', 'result2', 'result3', 'result4',
'result2', 'result1', 'result2', 'result6'],
'col6': [10, 20, 30, 40, 10, 20, 30, 40, 10, 20, 30, 50, 20, 100, 10, 10],
'col7': [100.2, 101.2, 102.3, 101.4, 100.0, 103.0, 104.0, 105.0, 102.0,
87.0, 107.0, 110.2, 120.0, 88.0, 106.2, 101.1]
})
ptable = df.pivot_table(values='col7', index=['col4'], columns=['col2'], aggfunc='max')
ptable = (ptable [(ptable >= 100).any(1)]
.fillna('')
.reset_index()
.rename_axis(None, axis=1))
一旦数据在 col2 上旋转,我正在尝试检索与最大值关联的行数据。我感兴趣的数据是 col5 和 col6 数据,但无法弄清楚如何获取该信息。非常感谢任何意见。
我要找的两个输出表如下:
请求的输出表#1:
| col4 | col5 | col6 | test1 | test2 | test3 | test4 | test5 |
|---|---|---|---|---|---|---|---|
| input1 | result2 | 10 | 106.2 | ||||
| input1 | result1 | 10 | 100 | 102 | |||
| input2 | result2 | 20 | 101.2 | 103 | 87 | 120 | |
| input3 | result3 | 30 | 102.3 | 104 | 107 | ||
| input4 | result4 | 40 | 101.4 | 105 | |||
| input5 | result4 | 50 | 110.2 |
请求的输出表#2:
| col4 | col5 | col6 | test1 | test2 | test3 | test4 | test5 |
|---|---|---|---|---|---|---|---|
| input1 | result2 | 10 | 106.2 | ||||
| input1 | result1 | 10 | 102.2 | 100 | 102 | ||
| input2 | result2 | 20 | 101.2 | 103 | 87 | 120 | |
| input3 | result3 | 30 | 102.3 | 104 | 107 | ||
| input4 | result4 | 40 | 101.4 | 105 | |||
| input5 | result4 | 50 | 110.2 |
提前致谢。
【问题讨论】:
标签: python pandas dataframe pivot-table