【问题标题】:Apply a fucntion with lambda to Pandas将带有 lambda 的函数应用于 Pandas
【发布时间】:2021-05-27 12:39:51
【问题描述】:

我有 2 个时间序列,我想从时间序列 1 到时间序列 2 的每个日期中找到最近的日期。我发现如何按日期单独执行此操作,但我想将其应用于整个时间序列1。它们位于两个不同的数据框中,称为 op

这是我的数据的样子: 时间序列1:

o['date']
>>>0    2020-01-26
1    2020-01-28
2    2020-01-31
3    2020-02-15
4    2020-02-17
        ...    
86   2021-01-10
87   2021-01-20
88   2021-01-27
89   2021-01-30
90   2021-02-14
Name: date, Length: 91, dtype: datetime64[ns]

时间序列2:

p['date']
>>>1     2020-02-17
3     2020-03-02
4     2020-03-03
5     2020-03-04
6     2020-03-05
         ...    
172   2021-01-30
173   2021-02-06
174   2021-02-07
177   2021-02-12
179   2021-02-14
Name: date, Length: 144, dtype: datetime64[ns]

我使用的函数:

def nearest(pivot,items):
    return min(items, key=lambda x: abs(x - pivot))

适用于单独的单数日期,例如:

nearest(o['date'][6], p['date'])
>>>Timestamp('2020-03-02 00:00:00')

当我尝试将其应用于整个 pandas Series 时,我收到一个错误:

o['date'].apply(nearest, args=(p['date']))
>>>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-82c86ffd48ff> in <module>()
----> 1 o['date'].apply(nearest, args=(p['date']))

C:\Users\ran\Anaconda3\envs\main\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   4180 
   4181         # handle ufuncs and lambdas
-> 4182         if kwds or args and not isinstance(func, np.ufunc):
   4183 
   4184             def f(x):

C:\Users\ran\Anaconda3\envs\main\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1325     def __nonzero__(self):
   1326         raise ValueError(
-> 1327             f"The truth value of a {type(self).__name__} is ambiguous. "
   1328             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1329         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我觉得我缺少一些基本的东西。

我想我能做到:

[nearest(x, p['date']) for x in o['date']]

但我想知道如何将其应用于Pandas Series

【问题讨论】:

    标签: python-3.x pandas dataframe datetime


    【解决方案1】:

    Series.apply 与 lambda 函数一起使用:

    s = o['date'].apply(lambda x: nearest(x, p['date']))
    

    或者用args参数:

    s = o['date'].apply(nearest, args=(p['date'], ))
    

    numpy.argmin 的 Numpy 替代方案应该更快:

    a = o['date'].to_numpy() 
    b = p['date'].to_numpy()
    pos = np.argmin(np.abs(a- b[:, None]), axis=0)
    
    s = pd.Series(b[pos], index=o.index)
    

    【讨论】:

    • 谢谢 - s = o['date'].apply(lambda x: nearest(x, p['date'])) 这是我所缺少的基本内容
    猜你喜欢
    • 2018-06-19
    • 2012-08-24
    • 2013-11-15
    • 2016-03-20
    • 2018-06-26
    • 2022-01-27
    • 2014-02-06
    相关资源
    最近更新 更多