I have a .csv file of 8k+ rows which looks like this:
state assembly candidate \
0 Andaman & Nicobar Islands Andaman & Nicobar Islands BISHNU PADA RAY
1 Andaman & Nicobar Islands Andaman & Nicobar Islands KULDEEP RAI SHARMA
2 Andaman & Nicobar Islands Andaman & Nicobar Islands SANJAY MESHACK
3 Andaman & Nicobar Islands Andaman & Nicobar Islands ANITA MONDAL
4 Andaman & Nicobar Islands Andaman & Nicobar Islands K.G.DAS
party votes
0 Bharatiya Janata Party 90969
1 Indian National Congress 83157
2 Aam Aadmi Party 3737
3 All India Trinamool Congress 2283
4 Communist Party of India (Marxist) 1777
The end dataframe I wanted to get was one which contains all the states as rows and two columns - one which has votes received by a particular party ("Bhartiya Janata Party"
, in this case) in that row's state and another which has the total votes from the state. Like this:
State Total Votes BJP Votes
Andaman & Nicobar Islands 190328 90969.0
Andhra Pradesh 48358545 4091876.0
Arunachal Pradesh 596956 275344.0
Assam 15085883 5507152.0
Bihar 35885366 10543023.0
My code works but I'm pretty sure there's a much better way to get this done using fewer lines of code and without creating too many dataframes. Here's my code:
dff = df.groupby(['party'])[['votes']].agg('sum')
dff = dff.sort_values('votes')
BJP_df = df[df["party"]=="Bharatiya Janata Party"]
#print(BJP_df.head())
group = BJP_df.groupby(['state'])[['votes']].agg('sum')
state = df.groupby(['state'])[['votes']].agg('sum')
result = pd.concat([state, group], axis = 1, sort=False)
result.columns = ["Total Votes","BJP Votes"]
Any tips, suggestions, pointers would be very much appreciated.