Coding Ref

How to use ewm() in Pandas

How to use ewm() in Pandas

The ewm() function in Pandas is used to apply exponential weighting to a series or dataframe.

This is often used to compute an exponentially weighted moving average, which gives more weight to more recent values and less weight to older values.

Example

Here's an example of using the ewm() function in Pandas:

main.py
import pandas as pd

# create a sample series
s = pd.Series([1, 2, 3, 4, 5])

# compute the exponentially weighted moving average of the series
s_ewm = s.ewm(alpha=0.5).mean()

# display the result
print(s_ewm)

This will compute the exponentially weighted moving average of the series and return a new series with the same index as the original series.

The alpha parameter specifies the decay factor, which determines the weight of each value in the moving average.

The output will be:

output
0    1.000000
1    1.666667
2    2.428571
3    3.266667
4    4.161290
dtype: float64

Using ewm() on one or more columns

You can also use the ewm() function on a dataframe to compute the exponentially weighted moving average of one or more columns.

For example:

main.py
# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3, 4, 5],
                   "B": [2, 3, 4, 5, 6]})

# compute the exponentially weighted moving average of the A and B columns
df_ewm = df[["A", "B"]].ewm(alpha=0.5).mean()

# display the result
print(df_ewm)

This will compute the exponentially weighted moving average of the A and B columns in the dataframe and return a new dataframe with the same index as the original dataframe.

The output will be:

output
          A         B
0  1.000000  2.000000
1  1.666667  2.666667
2  2.428571  3.428571
3  3.266667  4.266667
4  4.161290  5.161290

Conclusion

The ewm() function is useful for computing the exponentially weighted moving average of a series or dataframe, which can be useful for a variety of analysis and visualization tasks.

You'll also like

Related tutorials curated for you

    How to find the mode in a Pandas DataFrame

    How to GroupBy Index in Pandas

    How to use intertuples() in Pandas

    How to add an empty column to a Pandas DataFrame

    What does Diff() do in Pandas?

    How to reset index in a Pandas DataFrame

    How to calculate the variance in Pandas DataFrame

    How to use Timedelta in Pandas

    What is idxmax() in Pandas?

    How to convert a series to a NumPy array in Pandas

    How to use astype() in Pandas

    How to give multiple conditions in loc() in Pandas