繁体   English   中英

编写一个pandas / python函数,它需要在pandas数据帧中输入多个列

[英]write a pandas/python function which requires as inputs multiple columns in a pandas dataframe

在具有两列的数据帧中,如果它是数字运算,例如乘法df [“new”] = df [“one”] * df [“two”],我可以很容易地创建没有函数的第三个。

但是,如果我需要将两个以上的参数传递给函数,那些参数是来自数据帧的列。

使用一次传递一列很简单:df.apply(my_func)但是如果函数定义是,并且需要三列:

def WordLength(col1,col2,col3):
return max(len(col1),len(col2),len(col3))

例如,函数WordLength将从传入其中的三列中的任何一列返回单词的最大长度。

我知道例如这不起作用,但我想像这样的东西将一个需要三个参数的函数的结果返回到一个dataframe列:

df["word_length"]= df.apply(WordLength, [[param1,param2,param3]])

更新 Jon,当尝试使用传递三个参数的方法时(给定行的三个数据帧列的值,我收到以下错误:

def get(name,start_date,end_date):
    try:
        df = ...

response = df.apply(get, axis=1, args=('name', 'date', 'today')) 

与参数有关的错误 - 我不明白为什么它在我传入三个时提到了4个参数,而且函数只需要三个参数......

错误:

TypeError:('getprice()正好接受3个参数(4个给定)',u'occurred at index 0')

我认为你的申请需要一个lambda函数:

def WordLength(words):
    return max(len(words[0]),len(words[1]),len(words[2]))

df['wordlength'] = df[['col1','col2','col3']].apply(lambda x: WordLength(x),axis=1)

输出:

    col1            col2        col3                wordlength
0   word1           word10      wordover9000        12
1   anotherword     wooooord    test                11
2   yetanotherword  letter      Ihavenootheridea    16

除非您真的想要一个函数来执行此操作,否则您可以使用DataFrame操作,例如:

df[['col1', 'col2', 'col3']].applymap(len).max(axis=1)

您可以使用applyargs参数传入要处理的列,并使目标函数采用可变数量的参数进行解包,例如:

def max_word_length(row, *cols):
    return row[list(cols)].map(len).max()

# Make sure `axis=1` so rows are passed in and we can access columns
df.apply(max_word_length, axis=1, args=('col1', 'col2', 'col3'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM