【问题标题】:Python Pandas using lambda on index row by rowPython Pandas 在索引上逐行使用 lambda
【发布时间】:2016-12-21 04:09:29
【问题描述】:

所以我正在尝试将函数逐行应用于索引但遇到了一些问题

startDate = '2015-05-01 00:00'
endDate = '2015-05-08 00:00'
idx = pd.date_range(startDate, endDate, freq="1min")
df = pd.DataFrame(columns=['F(t)'])
df = df.reindex(idx, fill_value=0)

def circadian_function(T):
    return math.cos(math.pi*(T-delta)/12)

到目前为止一切正常,但尝试应用该功能我不知道该怎么做

df['F(t)'] = df.index.apply(lambda x: circadian_function x[index].hour, axis=1)

我应该使用 lambda 吗?还是只是申请?

【问题讨论】:

    标签: python pandas lambda apply


    【解决方案1】:

    我没有 50 个代表,所以我无法评论 @Ted Petrou 的回答 ;-; 我只是想说几件你应该知道的事情。

    1. 如果您要将df.index.hour 输入carcadian_function,请确保使用numpy 而不是math。否则解释器会抛出一个TypeError(我刚刚发现了这个)。

    2. 确保定义delta

    例子:

    import numpy as np
    
    def circadian_function(T, delta):
        return np.cos(np.pi * (T-delta) / 12)
    

    @Ted Petrou 建议您做的全部内容:

    df['F(x)'] = circadian_function(df.index.hour, 0.5) #I picked an arbitrary delta
    

    Numpy 会自动为你向量化函数。给 Ted 的道具我也学到了一些新东西:>

    【讨论】:

    • 忘记增量,我在代码中定义 delta=18,但是 df['F(x)'] = circadian_function(df.index.hour) 给出错误 TypeError: only length-1数组可以转换为 Python 标量
    • 这就是为什么您应该将math 更改为numpy,或者在我的示例中为np
    【解决方案2】:

    仅使用 apply 作为最后一个结果。这可以很容易地向量化。确保你定义了 delta。

     import numpy as np
     df['F(t)'] = np.cos(np.pi*(idx.hour-delta)/12)
    

    【讨论】:

    • 什么意思?这 df['F(t)'] = df.apply(math.cos(math.pi*(idx.hour-delta)/12)) 不起作用(即使在定义 delta 之后)
    • 这也不起作用 df['F(t)'] = df['F(t)'].apply(math.cos(math.pi*(df.index.hour -delta)/12))
    • 这也不起作用 df['F(t)'] = df.index.apply(math.cos(math.pi*(idx.hour-delta)/12))
    • 还有其他人知道如何为这个问题提供有效的答案吗?
    • 立即尝试。我添加了 dt 访问器
    猜你喜欢
    • 2020-07-01
    • 2021-07-14
    • 2017-12-08
    • 1970-01-01
    • 2020-01-02
    • 2019-10-07
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多