1

Ihave a DataFrame, looks like this:

    Date            Price
0   Jan 04, 1999    1.1827
1   Jan 05, 1999    1.1764
2   Jan 06, 1999    1.1618
3   Jan 07, 1999    1.1709
4   Jan 08, 1999    1.1575
5   Jan 11, 1999    1.1502
6   Jan 12, 1999    1.1572
7   Jan 13, 1999    1.1673
8   Jan 14, 1999    1.1698
9   Jan 15, 1999    1.1557

I would like to add a new column, which counted in Excel like this: =IF((B2-B1)>0;B2-B1;0), so it should look like this:

    Date            Price   up
0   Jan 04, 1999    1.1827  0.0000
1   Jan 05, 1999    1.1764  0.0000
2   Jan 06, 1999    1.1618  0.0000
3   Jan 07, 1999    1.1709  0.0091
4   Jan 08, 1999    1.1575  0.0000
5   Jan 11, 1999    1.1502  0.0000
6   Jan 12, 1999    1.1572  0.0070
7   Jan 13, 1999    1.1673  0.0101
8   Jan 14, 1999    1.1698  0.0025
9   Jan 15, 1999    1.1557  0.0000

Actually, I have a solution, but I am not satisfied with it:

ser=[]
i = 0
while i < len(df["Price"]):
    if i==0:
        ser.append(0)
    elif df["Price"][i]-df["Price"][i-1]>0:
        ser.append((df["Price"][i]-df["Price"][i-1]))
    else:
        ser.append(0)
    i = i+1
df["up"]=ser

Is there any more elegant solution? Thanks!

0

1 Answer 1

2

Use diff with where:

dif = df['Price'].diff()
df['up'] = dif.where(dif > 0, 0)
#alternative
#df['up'] = np.where(dif > 0, dif, 0)
print (df)
           Date   Price      up
0  Jan 04, 1999  1.1827  0.0000
1  Jan 05, 1999  1.1764  0.0000
2  Jan 06, 1999  1.1618  0.0000
3  Jan 07, 1999  1.1709  0.0091
4  Jan 08, 1999  1.1575  0.0000
5  Jan 11, 1999  1.1502  0.0000
6  Jan 12, 1999  1.1572  0.0070
7  Jan 13, 1999  1.1673  0.0101
8  Jan 14, 1999  1.1698  0.0025
9  Jan 15, 1999  1.1557  0.0000
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.