python - function that takes one column value and returns another column value -
apologies, if 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 attempting create function take particular column 1 value input , output column 1 value corresponding column 2 values.
for example, if used function when column 1 equal 3, function return list of 4 values: 3, 10, 11, 12
many thanks
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): = 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 else: #for match 1 value 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
Comments
Post a Comment