python - 减去具有不同索引的熊猫系列
问题描述
我有一个数据框,其中包含以下条目的集合:(日期,卷)。
我想创建一个新的数据框列,其中 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)]
解决方案
它似乎在抱怨使用分组的 month_means 和 df['Volume'] 的原始(日期时间)索引进行索引。为避免索引问题,您可以删除x.values
用于每个系列的不同索引。
df['spread_monthly'] = df['Volume'].values - month_means[zip(df.index.year, df.index.month)].values
改为这样做。
推荐阅读
- javascript - d3js 搜索节点及其子节点
- android - Android WorkManager:是否可以设置任务的最大执行持续时间
- reactjs - npx serve 提供主目录而不是 index.html
- python - 将数据堆叠到具有两个标题的行中,并且第一个标题不合并
- windows - Windows libvirt/QEMU 来宾虚拟机在重新启动后将时区重置为主机时区
- r - 在 R 中将字母映射到数字
- python - openCV库中的getPerspectiveTransform()函数是如何找到变换矩阵的?
- kubernetes - NodePort 与 kube-apiserver 的 hostPort 冲突
- c++ - 访问另一个类中的一个类成员
- css - 使用css隐藏div内的div元素