Python 按行和列和子集df
我有一个按县划分的候选人提名df。(600 X 1192) 我需要将原始df子集,以选择总votation>50(行和)的候选项和总votation>100(列和)的Countys 根据原始数据,我没有按候选人、县列出的总数Python 按行和列和子集df,python,pandas,Python,Pandas,我有一个按县划分的候选人提名df。(600 X 1192) 我需要将原始df子集,以选择总votation>50(行和)的候选项和总votation>100(列和)的Countys 根据原始数据,我没有按候选人、县列出的总数 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"
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
结果必须是:
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
非常感谢您帮助解决我的问题使用布尔索引:
df1.set_index(['candidate', 'code']).loc[
lambda x: x.sum(axis=1) > 50, lambda x: x.sum(axis=0) > 100
]
lambda允许操作员链接,但如果您想要更干净的方式,也可以这样做
df1 = df1.set_index(['candidate', 'code'])
df1.loc[df1.sum(axis=1) > 50, df1.sum(axis=0) > 100]
两者都屈服
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
其中候选列和代码列是DataFrame的索引。如果希望它们作为常规列,可以在末尾调用reset\u index()