Skip to main content
 首页 » 编程设计

python之如何应用一个使用两个系列作为输入的函数,输出是每个参数组合的函数结果的数据帧

2024年11月24日13cmt

我有两个系列,每个系列都包含我想在函数中使用的变量。我想为每个变量组合应用函数,结果输出是计算值的 DataFrame,索引将是一个系列的索引,列将是另一个系列的索引。

我曾尝试寻找类似问题的答案 - 我确定有一个答案,但我不确定如何为搜索引擎描述它。

我已经通过使用 for 循环创建函数解决了这个问题,因此您可以理解其中的逻辑。我想知道是否有更有效的操作可以在不使用 for 循环的情况下执行此操作。

从我读到的内容来看,我正在想象列表理解与压缩列的某种组合来计算值,然后将其 reshape 为 DataFrame,但我无法通过这种方式解决。

这是重现问题的代码和当前的解决方案。

import pandas as pd 
 
bands = pd.Series({'A': 5, 'B': 17, 'C': 9, 'D': 34}, name='band') 
values = pd.Series({'Jan': 1, 'Feb': 1.02, 'Mar': 1.05, 'Apr': 1.12}, name='values') 
 
# Here is an unused function as an example 
myfunc = lambda x, y: x * (1 + 1/y) 
 
def func1(values, bands): 
    # Initialise empty DataFrame 
    df = pd.DataFrame(index=bands.index,  
                             columns=values.index) 
 
    for month, month_val in values.iteritems(): 
        for band, band_val in bands.iteritems(): 
            df.at[band, month] = band_val * (1/month_val - 1) 
 
    return df 
 
outcome = func1(values, bands) 

请您参考如下方法:

你可以使用 numpy.outer为此:

import numpy as np 
import pandas as pd 
 
bands = pd.Series({'A': 5, 'B': 17, 'C': 9, 'D': 34}, name='band') 
values = pd.Series({'Jan': 1, 'Feb': 1.02, 'Mar': 1.05, 'Apr': 1.12}, name='values') 
 
outcome = pd.DataFrame(np.outer(bands, ((1 / values) - 1)), 
                       index=bands.index, 
                       columns=values.index) 

[输出]

   Jan       Feb       Mar       Apr 
A  0.0 -0.098039 -0.238095 -0.535714 
B  0.0 -0.333333 -0.809524 -1.821429 
C  0.0 -0.176471 -0.428571 -0.964286 
D  0.0 -0.666667 -1.619048 -3.642857 

作为函数:

def myFunc(ser1, ser2): 
    result = pd.DataFrame(np.outer(ser1, ((1 / ser2) - 1)), 
                          index=ser1.index, 
                          columns=ser2.index) 
    return result 
 
myFunc(bands, values)