I have a df for candidates votations by county. (600 X 1192)
I need to subset the original df to select the candidates with total votation > 50 (row sum) and Countys with total votation > 100 (column sum)
On the original data I do not have the totals by candidate, county.
import pandas as pd
import numpy as np
df1 = pd.DataFrame([["cand1", 10,100, 1, 1000, 10, 100],["cand2",20,1000, 2, 20, 0, 20],["cand3", 30,5000, 3, 30, 0, 3], ["cand4",40, 1, 4, 1, 0, 4], ["cand5",50, 50, 0,20, 0,2]],
columns=['candidate',"code", 'county1', 'county2', 'county3', 'county4', 'county5'])
df1
And the result must be:
df2 = pd.DataFrame([["cand1", 10,100, 1000, 100],["cand2",20,1000, 20, 20],["cand3",30, 5000, 30, 3], ["cand5",50, 50, 20, 2]],
columns=['candidate',"code", 'county1', 'county3', 'county5'])
df2
I would appreciate your help to solve my issue
Use boolean indexing:
df1.set_index(['candidate', 'code']).loc[
lambda x: x.sum(axis=1) > 50, lambda x: x.sum(axis=0) > 100
]
lambdas allow operator chaining but if you want a cleaner way you can also do
df1 = df1.set_index(['candidate', 'code'])
df1.loc[df1.sum(axis=1) > 50, df1.sum(axis=0) > 100]
Both yield
county1 county3 county5
candidate code
cand1 10 100 1000 100
cand2 20 1000 20 20
cand3 30 5000 30 3
cand5 50 50 20 2
where candidate and code columns are the index of DataFrame. You can call reset_index()
at the end if you want them as regular columns.
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.