python - 尝试根据与数据框相关的 if 语句在 Pandas 中创建新的数据框列

标签 python function pandas dataframe

我正在学习 Python 和 Pandas,并练习不同的股票计算。我曾尝试搜索这方面的帮助,但只是没有找到足够相似的响应,或者不明白如何根据以前的响应推断出正确的方法。

我已经使用 DataReader 将给定时间范围内的股票数据读取到数据框 df 中。在 df 中,我有 Date Volume 和 Adj Close 列,我想使用它们根据给定的条件创建一个新列“OBV”。 OBV 是一个累积值,它根据调整后的收盘价将今天的交易量值加到前几天的 OBV 上。

OBV的计算很简单:

如果今天的调整收盘价高于昨天的调整收盘价,则将今天的交易量添加到昨天的(累积)交易量中。

如果今天的调整收盘价低于昨天的调整收盘价,则从昨天的(累积)交易量中减去今天的交易量。

第 1 天 OBV = 0

然后在时间范围内重复此过程并累积 OBV。

这是基本的导入和开始

import numpy as np
import pandas as pd
import pandas_datareader

import datetime
from pandas_datareader import data, wb

start = datetime.date(2012, 4, 16)
end = datetime.date(2017, 4, 13)

# Reading in Yahoo Finance data with DataReader
df = data.DataReader('GOOG', 'yahoo', start, end)

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#This is what I cannot get to work, and I've tried two different ways.

#ATTEMPT1

def obv1(column):
    if column["Adj Close"] > column["Adj close"].shift(-1):
        val = column["Volume"].shift(-1) + column["Volume"]
    else:
        val = column["Volume"].shift(-1) - column["Volume"] 
    return val

df["OBV"] = df.apply(obv1, axis=1)

#ATTEMPT 2

def obv1(df):
    if df["Adj Close"] > df["Adj close"].shift(-1):
        val = df["Volume"].shift(-1) + df["Volume"]
    else:
        val = df["Volume"].shift(-1) - df["Volume"] 
    return val

df["OBV"] = df.apply(obv1, axis=1)

两者都给我一个错误。

最佳答案

考虑数据框 df

np.random.seed([3,1415])
df = pd.DataFrame(dict(
        Volume=np.random.randint(100, 200, 10),
        AdjClose=np.random.rand(10)
    ))

print(df)

   AdjClose  Volume
0  0.951710     111
1  0.346711     198
2  0.289758     174
3  0.662151     190
4  0.171633     115
5  0.018571     155
6  0.182415     113
7  0.332961     111
8  0.150202     113
9  0.810506     126

AdjClose 的变化为负时,将 Volume 乘以 -1。然后 cumsum

(df.Volume * (~df.AdjClose.diff().le(0) * 2 - 1)).cumsum()

0    111
1    -87
2   -261
3    -71
4   -186
5   -341
6   -228
7   -117
8   -230
9   -104
dtype: int64

将此与 df

的其余部分一起包括在内
df.assign(new=(df.Volume * (~df.AdjClose.diff().le(0) * 2 - 1)).cumsum())

   AdjClose  Volume  new
0  0.951710     111  111
1  0.346711     198  -87
2  0.289758     174 -261
3  0.662151     190  -71
4  0.171633     115 -186
5  0.018571     155 -341
6  0.182415     113 -228
7  0.332961     111 -117
8  0.150202     113 -230
9  0.810506     126 -104

关于python - 尝试根据与数据框相关的 if 语句在 Pandas 中创建新的数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455763/

相关文章:

python - 在 Gtk+ 程序中嵌入 IPython shell

python - 将状态传递给函数与调用类实例上的方法

javascript - 将多个处理程序绑定(bind)到元素

python - 有没有办法使用索引和列名作为键从 Pandas 数据框中创建键值对字典?

python - 根据用户输入绘制特定列

python - 如何使 python 要求可移植?

python - 使用 exe pyinstaller 包含一个 json 文件

javascript - 将函数传递给方法时,为什么使用匿名函数容器而不只是原始函数可以工作?

python - 使用 lambda 函数拆分 Pandas 数据集中的列