Reputation: 373
I have a data like
Date, Name, Something
2020-04-01,John,10
2020-04-01,Ivory,5
2020-04-01,Sam,3
2020-04-02,John,5
2020-04-02,Ivory,2
2020-04-02,Sam,1
2020-04-02,John,20
2020-04-02,Ivory,3
2020-04-02,Sam,9
working with pandas, i want to compare yesterday value by name, with today result to get the increase, decrease. shift(3) won't work because number of names are different for each day. How can i do it. I want to add previous number. I tried
df['old_data'] = df[(work['Name'] == df['Name']) & (df['Date'] ==
(df['Date'] - pd.Timedelta(days = 1))
)]['Something']
but it didn't work.
Upvotes: 0
Views: 352
Reputation: 354
Try this:
import pandas as pd
df = pd.DataFrame({'Date': {0:'2020-04-01', 1:'2020-04-01', 2:'2020-04-01',
3:'2020-04-02', 4:'2020-04-02', 5:'2020-04-02',
6:'2020-04-03', 7:'2020-04-03', 8:'2020-04-03'},
'Name': {0:'John', 1:'Ivory', 2:'Sam',
3:'John', 4:'Ivory', 5:'Sam',
6:'John', 7:'Ivory', 8:'Sam'},
'Something': {0:10, 1:5, 2:3,
3:5, 4:2, 5:1,
6:20, 7:3, 8:9}})
df['diff'] = df.groupby('Name')['Something'].diff()
df.dropna()
I changed your data by altering the last three dates to be '2020-04-03'.
Upvotes: 2