0

Is it possible to grab a given value in a Pandas column and change it to a previous row value?

For instance, I have this Dataframe:

Date Price Signal 2018-01-01 13380.00 1 2018-01-02 14675.11 0 2018-01-03 14919.51 0 2018-01-04 15059.54 0 2018-01-05 16960.39 0 2018-01-06 17069.79 -1 2018-01-07 16150.03 0 2018-01-08 14902.54 0 2018-01-09 14400.00 1 2018-01-10 14907.09 0 2018-01-11 13238.78 0 2018-01-12 13740.01 -1 2018-01-13 14210.00 0

I would like to replace the zeros in the Signal column for either 1 or -1. The final DF should be this:

Date Price Signal 2018-01-01 13380.00 1 2018-01-02 14675.11 1 2018-01-03 14919.51 1 2018-01-04 15059.54 1 2018-01-05 16960.39 1 2018-01-06 17069.79 -1 2018-01-07 16150.03 -1 2018-01-08 14902.54 -1 2018-01-09 14400.00 1 2018-01-10 14907.09 1 2018-01-11 13238.78 1 2018-01-12 13740.01 -1 2018-01-13 14210.00 -1
Ronnie Ron
  • 13
  • 2
  • Does this answer your question? [How to replace NaNs by preceding values in pandas DataFrame?](https://stackoverflow.com/questions/27905295/how-to-replace-nans-by-preceding-values-in-pandas-dataframe) – MrNobody33 Aug 18 '20 at 17:39

3 Answers3

0

If what you want is propagate previous values to the next rows use the following:

df["Signal"] = df["Signal"].ffill()
Let's try
  • 1,044
  • 9
  • 20
0

Try this:

df['Signal'].replace(to_replace=0, method='ffill')

(assuming your DataFrame is callled df)

Ricardo Rendich
  • 666
  • 5
  • 6
0
import pandas as pd

Prepare a dataframe

If you have a dataframe:

df = pd.DataFrame([1,0,1,0,1], columns=['col1'])

enter image description here


Use pure apply()

You can do:

def replace(num):
    if num==1: return 1
    if num==0: return -1

Then apply it to the column holding the values you want to replace:

df['new']=df['col1'].apply(replace)

apply() lambda functions

You can achieve the same with a lambda function:

df['col1'].apply(lambda row: 1 if row == 1 else -1)

Use Built-in methods

Using the dataframe we prepared, can do:

df['new'] = df['col1'].replace(to_replace=0, value=-1)

If you don't want to create a new column, just straight replace the the values in the existing one, can do it inplace:

df['col1'].replace(to_replace=0, value=-1,inplace=True)

Clean up

If created a new column & don't want to keep the old column, can drop it:

df.drop('col1',axis=1)
zabop
  • 6,750
  • 3
  • 39
  • 84