从列A获取列名,然后将该列的值保存在新列C中

时间:2018-08-31 06:04:25

标签: python pandas

我有一个如下所示的pandas数据框:(它基于图像分析,并使用3种不同的算法以及其置信度来猜测图像是什么)

p1    p1_conf   p2    p2_conf   p3       p3_conf
dog   0.45      cat   0.32      book     0.05
dog   0.01      book  0.9       table    0.5
...

最终目标是找到最佳预测(置信度最高的预测):即第一行是狗,第二行是书。

我已使用以下代码查找最大置信度和具有最大置信度的列的名称:

df['max_conf'] = df[['p1_conf', 'p2_conf', 'p3_conf']].max(axis=1)
df['max_col'] = df[['p1_conf', 'p2_conf', 'p3_conf']].idxmax(axis=1)
df['pred_algorithm'] = df['max_col'].apply(lambda x: x.split('_')[0])

现在我的数据框看起来像这样:

p1    p1_conf   p2    p2_conf   p3       p3_conf   max_conf   pred_algorithm
dog   0.45      cat   0.32      book     0.05      0.45       p1
dog   0.01      book  0.9       table    0.5       0.9        p2
...

现在,我需要使用pred_algorithm列为每一行找到最佳预测。

我尝试过:

df['best_prediction'] = df[df['pred_algorithm']]

,我收到以下错误消息:

ValueError: Wrong number of items passed 1691, placement implies 1

如何创建新列?

1 个答案:

答案 0 :(得分:1)

可以通过lookup使用另一个列值来从列中选择值:

df['best_prediction'] = df.lookup(df.index, df['pred_algorithm'])

结果数据框:

p1  p1_conf p2   p2_conf p3   p3_conf max_conf pred_algorithm best_prediction
0   dog     0.45 cat     0.32 book    0.05     0.45 p1        dog
1   dog     0.01 book    0.90 table   0.50     0.90 p2        book