簡體   English   中英

resampling.agg/.apply 行為

[英]resampling .agg/.apply behavior

這個問題與 resample .agg/.apply ,它的行為不同於 groupby .agg/.apply

這是一個示例 df:

df = pd.DataFrame({'A':range(0,100),'B':range(0,200,2)},index=pd.date_range('1/1/2022',periods=100,freq='D'))

Output:

             A    B
2022-01-01   0    0
2022-01-02   1    2
2022-01-03   2    4
2022-01-04   3    6
2022-01-05   4    8
...         ..  ...
2022-04-06  95  190
2022-04-07  96  192
2022-04-08  97  194
2022-04-09  98  196
2022-04-10  99  198

我的問題是, x在下面的apply function中代表什么。 有時它表現為系列,有時表現為 df。 通過調用type(x)它返回df 但是,下面會返回一條錯誤"No axis named 1 for object type Series"

df.resample('M').apply(lambda x: x.sum(axis=1))

但事實並非如此。 系列沒有堆棧,因此這意味着x代表df

df.resample('M').apply(lambda x: x.stack())

此外,當您運行df.resample('M').apply(lambda x: print(type(x)))時,輸出是系列,但df.resample('M').apply(lambda x: type(x))輸出 dataframe 類型。

所以我的主要問題是,傳遞給 apply for resample的是什么。 series還是dataframe

這是一個非常好的問題,但我想我沒有正確的答案。

  1. 對時間序列resample返回一個DatetimeIndexResampler實例。
  2. applyaggregate function 的別名。

現在檢查源代碼

    @doc(
        _shared_docs["aggregate"],
        see_also=_agg_see_also_doc,
        examples=_agg_examples_doc,
        klass="DataFrame",
        axis="",
    )
    def aggregate(self, func=None, *args, **kwargs):


        result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
        if result is None:
            how = func
            result = self._groupby_and_aggregate(how, *args, **kwargs)


        result = self._apply_loffset(result)
        return result


    agg = aggregate
    apply = aggregate

我的理解:我認為如果ResamplerWindowApply出現問題, aggregate function 有一個回退機制來重新評估 function 和_groupby_and_aggregate

最后一個的文檔字符串是:

"""
Re-evaluate the obj with a groupby aggregation.
"""

讓我們用一個名為 function 的調試:

import inspect

def f(x):
    print(inspect.stack()[2].function)
    print(f'begin: {type(x)}')
    x.stack()
    print(f'end: {type(x)}')
    return x.sum(axis=1)

df.resample('M').apply(f)

Output:

_aggregate_series_pure_python
begin: <class 'pandas.core.series.Series'>  # something goes wrong
_python_apply_general  # the caller has changed
begin: <class 'pandas.core.frame.DataFrame'>  # now x is a DataFrame
end: <class 'pandas.core.frame.DataFrame'>
_python_apply_general
begin: <class 'pandas.core.frame.DataFrame'>
end: <class 'pandas.core.frame.DataFrame'>
_python_apply_general
begin: <class 'pandas.core.frame.DataFrame'>
end: <class 'pandas.core.frame.DataFrame'>
_python_apply_general
begin: <class 'pandas.core.frame.DataFrame'>
end: <class 'pandas.core.frame.DataFrame'>

Series失敗后, aggregate調用 function 和DataFrame 不幸的是,沒有記錄這種行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM