Python 函数,该函数接受一个列值并返回另一个列值

Python 函数,该函数接受一个列值并返回另一个列值,python,function,pandas,Python,Function,Pandas,抱歉,如果这是重复的请让我知道,我很乐意删除 我的数据集: 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个值的列表:

抱歉,如果这是重复的请让我知道,我很乐意删除

我的数据集:

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

非常感谢

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
但如果需要更一般的:

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

只是一个简单的函数:

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

只是一个简单的函数:

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