Ivan
Ivan

Reputation: 7746

apply to a rolling window function loses column names

I have a function that takes a dataframe:

def max_dd(df):
    print(df)

    return None

If I print df.head() before passing it to max_dd, it looks like this:

print(df.head())

            Close
Date
2010-08-10   7.95
2010-08-11   7.67
2010-08-12   7.72
2010-08-13   7.64
2010-08-16   7.59

However if I now pass df to max_dd,

new = df.rolling(45).apply(max_dd)

The function prints:

Date
2010-08-10    7.95
2010-08-11    7.67
2010-08-12    7.72
2010-08-13    7.64
2010-08-16    7.59

Why did it lose the Close column name and how do I get it back?

Upvotes: 1

Views: 152

Answers (1)

Corralien
Corralien

Reputation: 120409

Rolling.apply func does not receive a DataFrame as parameter but a Series:

def max_dd(df):
    print(df)
    print(type(df))

    return None

new = df.rolling(45).apply(max_dd)

Output:

Date
2010-08-10    7.95
2010-08-11    7.67
2010-08-12    7.72
2010-08-13    7.64
2010-08-16    7.59
dtype: float64
<class 'pandas.core.series.Series'>  # <- Not a DataFrame but a Series

Upvotes: 1

Related Questions