【问题标题】:How to apply a function using two Series as input with the output being a DataFrame of the function result of each combination of arguments?如何使用两个系列作为输入应用函数,输出是每个参数组合的函数结果的 DataFrame?
【发布时间】:2019-06-07 13:53:11
【问题描述】:

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

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

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

根据我所阅读的内容,我正在想象某种列表理解与压缩列的组合来计算值,然后将其重新整形为 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)

【问题讨论】:

    标签: python pandas apply


    【解决方案1】:

    您可以为此使用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)
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多