简体   繁体   English

如何根据 Pandas dataframe 中上一行的行值创建新列?

[英]How to create a new column based on row value in previous row in Pandas dataframe?

I want to add a column which encodes a 1 if the Adjusted Closing Price of a stock at row T went up compared to the Adjusted Closing Price at row T-1, and encode a 0 if it went down instead.我想添加一个列,如果 T 行的股票的调整收盘价与 T-1 行的调整收盘价相比上涨,则编码为 1,如果它下跌,则编码为 0。

The dataframe looks like: dataframe 看起来像:

在此处输入图像描述

Eg, at row index 1298 for the new column should be 0例如,新列的行索引 1298 处应为 0

What's the best possible way to get this done (eg, via np.where()?) Any input is appreciated.完成这项工作的最佳方法是什么(例如,通过 np.where()?)任何输入都值得赞赏。

You can first sort_values on your date column to make sure they are in the right order to perform the comparison, and then you can use np.where with shift() to compare the previous value in Adj Close with the current one:您可以首先对日期列进行sort_values以确保它们以正确的顺序执行比较,然后您可以使用np.whereshift()将 Adj Close 中的前一个值与当前值进行比较:

# Sort by date
df.sort_values(by='Date',ascending=True)

# Create a column comparing previous Adj Close with current Adj Close
import numpy as np
df['i'] = np.where(df['Adj Close'].shift(1) < df['Adj Close'],1,0)

df
            Date        Open        High  ...  Adj Close    Volume  i
index                                     ...                        
1297  2021-03-01  104.540001  133.990005  ...     120.40  49597300  0
1298  2021-03-02  116.930000  133.199900  ...     118.18  33640400  0
1299  2021-03-03  122.500000  127.700000  ...     124.18  19173700  1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据上一行的值在熊猫数据框中创建一个新列 - Create a new column in a pandas dataframe based on values found on a previous row 如何使用基于上一行和下一行的条件在 Pandas Dataframe 上创建新列? - How can I create a new column on a Pandas Dataframe with conditions based on previous and next row? Python Pandas Dataframe 根据同一列中的前一行值计算新行值 - Python Pandas Dataframe calculating new row value based on previous row value within same column Pandas Dataframe基于前一行,将值添加到新列,但该列的最大值限于该列 - Pandas Dataframe Add a value to a new Column based on the previous row limited to the maximum value in that column 如何根据先前的行和列条件填充 pandas dataframe 的行? - How to populate row of pandas dataframe based on previous row and column condition? 如何在 pandas dataframe 中的特定行创建一个新列并插入值? - How to create a new column and insert value at a particular row in pandas dataframe? Pandas DataFrame:添加具有基于前一行计算值的新列 - Pandas DataFrame: Add new column with calculated values based on previous row 如何从 pandas dataframe 中的当前行中减去前一行以创建一个新列,以每个名称重新启动进程? - How to subtract previous row from current row in a pandas dataframe to create a new column restarting the process with each name? 根据上一个行值创建一个新列并删除当前行 - Create a new column based on previous row value and delete the current row 使用上一行用值创建新的Pandas DataFrame列 - Create New Pandas DataFrame Column with Values using Previous Row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM