Issue
I have a dataframe like below:
countryname yr US_Election_Year id_score Dem_Score
Albania 1992 1990 0.688809 0.366570
Albania 1997 1996 0.024751 0.247750
Argentina 1995 1992 0.081818 0.398908
Argentina 1999 1996 -0.521796 0.247759
Argentina 2003 2000 -0.293386 -0.102298
What I am trying to do is to take the difference between id_score
and next row value of Dem_Score
i.e.
id_score in ith row - Dem_Score in i+1 row for a given countryname
Eg. for the countryname
Argentina and for the yr
1999, the desired difference would be
0.081818 - 0.247759 = -0.165941
So the final dataframe should look like below:
countryname yr US_Election_Year id_score Dem_Score Delta_Dem_Dist
Albania 1992 1990 0.688809 0.366570
Albania 1997 1996 0.024751 0.247750 0.441130
Argentina 1995 1992 0.081818 0.398908
Argentina 1999 1996 -0.521796 0.247759 -0.165941
Argentina 2003 2000 -0.293386 -0.102298 -0.624094
So a simple df['id_score'] - df['Dem_Score'].shift(-1)
may not work.
Any clue on how to get the above approach for a given country?
Solution
Try:
df['Delta_Dem_Dist'] = df.groupby('countryname').apply(lambda x: x['id_score'].shift(1) - x['Dem_Score']).reset_index(drop=True)
Result:
countryname yr US_Election_Year id_score Dem_Score Delta_Dem_Dist
0 Albania 1992 1990 0.688809 0.366570 NaN
1 Albania 1997 1996 0.024751 0.247750 0.441059
2 Argentina 1995 1992 0.081818 0.398908 NaN
3 Argentina 1999 1996 -0.521796 0.247759 -0.165941
4 Argentina 2003 2000 -0.293386 -0.102298 -0.419498
This code groups the dataframe by countryname
, applies a lambda function to calculate the difference between id_score
and the next row’s Dem_Score
for each group, and then resets the index of the resulting dataframe.
And I think you made a small mistake in the last calculation in your desired output, I believe it should be -0.419498
instead of -0.624094
Answered By - canaytore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.