简体   繁体   English

使用Pandas数据框时用户定义的函数存在问题

[英]Issue with user defined functions when using Pandas Data Frames

I have encountered an issue when calling a user defined function when using Pandas DataFrames. 使用Pandas DataFrames时,在调用用户定义函数时遇到了问题。 Stock market data is read in from a SQLite3 database in the following form: 从SQLite3数据库以以下形式读取股市数据:

date high low close 日期高低收盘价

The following code sums high, low and close values for each row and adds a new column 'Sum' to df: 以下代码将每一行的高,低和关闭值相加,并向df添加新列“ Sum”:

def Sum(h, l, c):
    return h+l+c

df.loc[:, 'Sum'] = Sum(df['high'], df['low'], df['close'])

             high    low  close     Sum
date
2018-01-23  80.65  78.25  79.45  238.35
2018-01-24  81.65  79.50  80.50  241.65
2018-01-25  81.70  80.25  81.10  243.05
2018-01-26  81.25  78.25  78.75  238.25
2018-01-29  70.95  62.25  64.15  197.35

However, if the function is changed to return the maximum value of high, low, close for each row in df an error ("ValueError: The truth value of a Series is ambiguous.") is generated. 但是,如果更改函数以返回高,低,关闭df中的每一行的最大值,则会产生错误(“ ValueError:系列的真值不明确。”)。

def Max(h, l, c):
    return max(h, l, c)

df.loc[:, 'Max'] = Max(df['high'], df['low'], df['close'])

What is the issue with the Max function? Max函数有什么问题?

Jon Clements' comment is the way you should go. 乔恩·克莱门茨(Jon Clements)的评论是您应该采取的方式。 However, should you wish to perform more complex complications, pd.DataFrame.apply has this functionality: 但是,如果您希望执行更复杂的操作,则pd.DataFrame.apply具有以下功能:

Note I have renamed your function to avoid conflicts with built-in functions. 注意我已重命名您的函数,以避免与内置函数发生冲突。

def max_df(h, l, c):
    return max(h, l, c)

df['Max'] = df.apply(lambda row: max_df(row['high'], row['low'], row['close']), axis=1)

This is a good post to learn about these options, if you cannot vectorise your calculation: 如果您无法向量化计算,这是一篇了解这些选项的好文章:

Difference between map, applymap and apply methods in Pandas Pandas中map,applymap和apply方法之间的区别

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

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