2017-08-18 62 views
0

道歉,如果這是重複請讓我知道,我會很樂意刪除。函數需要一個列值並返回另一列值

我的數據集:

Index  Col 1  Col 2 

0   1  4, 5, 6 
1   2  7, 8, 9 
2   3  10, 11, 12 
3   4  13, 14, 15 

我試圖創建將採取特定列1值作爲其輸入和輸出的第1列的值與它的相應的列的2個值的函數。

例如,如果我用於當塔1等於3的函數,該函數將返回4個值的列表:3,10,11,12

非常感謝

回答

4
def f(a): 
    return df.loc[df['Col 1'] == a, 'Col 2'].item() 

但是,如果需要更通用的:

print (df) 
    Col 1  Col 2 
0  1  4, 5, 6 
1  1  7, 8, 9 
2  3 10, 11, 12 
3  4 13, 14, 15 

def f(a): 
    a = df.loc[df['Col 1'] == a, 'Col 2'] 
    #for no match 
    if a.empty: 
     return 'no match' 
    #for multiple match 
    elif len(a) > 1: 
     return a 
    else: 
    #for match one value only 
     return a.item() 

print (f(1)) 
0 4, 5, 6 
1 7, 8, 9 
Name: Col 2, dtype: object 

print (f(3)) 
10, 11, 12 

print (f(6)) 
no match 
0

只是一個簡單的功能:

def getColumn(col1): 
    beg = 1+3*col1 
    return [col1] + list(range(beg, beg+3)) 
相關問題