简体   繁体   中英

How do I gather information from 3 dataframes in pandas with custom headers?

I am learning pandas and doing some exercies but without much source

So basically I have these 4 dataframes below: 在此处输入图像描述

在此处输入图像描述

So for every bill in the dataset, i want to know how many legislators supported the bill and how many legislators opposed the bill, also who was the primary sponsor of the bill?

This is what I am trying to achieve: 在此处输入图像描述

I was able to solve this one: Is there a way to count how many entries exists with a certain filter for python pandas?

But what I'm asking now involves 3 tables I guess(?)

Use following loigc:

  • Join "bills" with "votes" on "bill_id"
  • Join "vote_results" to above on "vote_id"
  • Group by "bill_id"
  • Aggregate by filtering and counting by vote_type

I have assumed some dummy data:

bills = pd.DataFrame(data=[[1,"Bill #1","P1"],[2,"Bill #2","P2"]], columns=["id","title","Primary Sponsor"])

legislators = pd.DataFrame(data=[[1,"Legislator A"],[2,"Legislator B"],[3,"Legislator C"]], columns=["id","name"])

votes = pd.DataFrame(data=[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2]], columns=["id","bill_id"])

vote_results = pd.DataFrame(data=[[1,1,1,1],[2,2,2,2],[3,3,3,1],[4,1,4,1],[5,2,5,2],[6,3,6,2]], columns=["id","legislator_id","vote_id","vote_type"])


result_df = bills.merge(votes.rename(columns={"id": "vote_id"}), left_on="id", right_on="bill_id") \
                 .merge(vote_results.rename(columns={"vote_id": "vote_id2"}).drop("id", axis=1), left_on="vote_id", right_on="vote_id2") \
                 .groupby(["id","title","Primary Sponsor"]) \
                 .apply(lambda x: pd.Series({
                     "supporter_count": len([v for v in x.vote_type if v==1]),
                     "opposer_count": len([v for v in x.vote_type if v==2]),
                     })) \
                 .reset_index()

Output:

   id    title Primary Sponsor  supporter_count  opposer_count
0   1  Bill #1              P1                2              1
1   2  Bill #2              P2                1              2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM