Reputation: 195
Apologies, if this is a duplicate please let me know, I'll gladly delete.
My dataset:
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
I am attempting to create a function that will take a particular column 1 value as its input and output the column 1 value with its corresponding column 2 values.
For example, if I used the function for when column 1 is equal to 3, the function would return a list of 4 values: 3, 10, 11, 12
Many thanks
Upvotes: 0
Views: 1013
Reputation: 862641
def f(a):
return df.loc[df['Col 1'] == a, 'Col 2'].item()
But if need more general:
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
Upvotes: 4
Reputation: 1856
Just a simple function:
def getColumn(col1):
beg = 1+3*col1
return [col1] + list(range(beg, beg+3))
Upvotes: 0