接受一个列值并返回另一列值的函数 [英] function that takes one column value and returns another column value

查看:40
本文介绍了接受一个列值并返回另一列值的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,如果这是重复的邮件,请告诉我,我们很乐意删除.

Apologies, if this is a duplicate please let me know, I'll gladly delete.

我的数据集:

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列值.

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.

例如,如果我在第1列等于3时使用该函数,则该函数将返回4个值的列表:3、10、11、12

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

非常感谢

推荐答案

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

这篇关于接受一个列值并返回另一列值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆