【发布时间】:2020-06-10 17:12:20
【问题描述】:
给定一个包含 a1、b1 和 a2、b2 列的数据框,我想找到 a1、b1 中最大值的列索引,然后从 a2、b2 中获取具有相同相对列索引的值,如显示在下面的want 列中:
import pandas as pd
import numpy as np
# Sample data
df= pd.DataFrame({'a_1':[1,2,3], 'b_1': [2,1,3], 'a_2': [3,4,7], 'b_2':[5,6,8], 'want':[5, 4, 7]})
我能够做到这一点,但我不确定最后一步的最佳方法是什么:
# Get the argmax for a1, b1
df['c'] = df[['a_1', 'b_1']].idxmax(axis=1)
# Get the column index of the argmax
df['d'] = df['c'].apply(lambda x: ['a_1', 'b_1'].index(x))
这是问题的简化版本 - 实际上还有更多列可供搜索 - 例如a1-z1, a2-z2.
【问题讨论】:
标签: python pandas numpy multidimensional-array