首页 > 解决方案 > 减去具有不同索引的熊猫系列

问题描述

我有一个数据框,其中包含以下条目的集合:(日期,卷)。

我想创建一个新的数据框列,其中 Volume 列减去每月交易量的平均值。我想在熊猫中实现这一目标的方法是什么。

在下面,您可以找到上述设置:

import pandas as pd
import io
import numpy as np

df = pd.read_csv(io.StringIO(csv_file_content))
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')

# Get the means for each year/month pair
month_means = df.groupby([df.index.year, df.index.month])['Volume'].mean().round(2)

# I would like to subtract the Volume with the mean of its month.
df['spread_monthly'] = df['Volume'] - month_means[zip(df.index.year, df.index.month)]

标签: pythonpandasdataframe

解决方案


它似乎在抱怨使用分组的 month_means 和 df['Volume'] 的原始(日期时间)索引进行索引。为避免索引问题,您可以删除x.values用于每个系列的不同索引。

df['spread_monthly'] = df['Volume'].values - month_means[zip(df.index.year, df.index.month)].values改为这样做。


推荐阅读