2017-08-10 40 views
4
  1. 我有一個數據幀:如何獲得在列,其名稱在另一列在python保持的數據

    import pandas as pd 
    data = {'Alpha': [1, 2, 3, 4, 5], 'Beta':[6, 7 ,8, 9, 10], 
    'Delta': [11, 12, 13, 14, 15], 'Gamma': [16, 17, 18, 19, 20]} 
    df = pd.DataFrame(data, index = ['2010', '2011', '2012', '2013', '2014']) 
    df 
    

enter image description here

  • 它還有一個'選擇'欄,保存其他列名

    df['Select'] = ['Beta', 'Gamma', 'Gamma', 'Delta', 'Alpha'] 
    df 
    
  • enter image description here

  • 我需要添加的列,說的「選擇」,其中,數據將從,其名稱在被保持在列中導出「選擇」列,例如下面:

    df['Choice'] = [0,0,0,0,0] 
    row = df['Select'].values 
    for i in range(len(row)): 
        df['Choice'][i] = df[row[i]][i] 
    df 
    
  • enter image description here

  • 我正在使用循環,但也許有一些更優雅的方式?謝謝!
  • 回答

    4

    我們可以使用DataFrame.lookup()

    In [49]: df['new'] = df.lookup(df.index, df.Select) 
    
    In [50]: df 
    Out[50]: 
         Alpha Beta Delta Gamma Select Choice new 
    2010  1  6  11  16 Beta  6 6 
    2011  2  7  12  17 Gamma  17 17 
    2012  3  8  13  18 Gamma  18 18 
    2013  4  9  14  19 Delta  14 14 
    2014  5 10  15  20 Alpha  5 5 
    
    +0

    太好,太快 –

    +0

    @MaxU謝謝你,它的工作原理! – Karifan

    相關問題