Pandas Python-基于多个条件提取行。包括数据示例
我正在尝试根据条件将行从dataframe1提取到dataframe2,但我正在努力,有人能帮我吗?那太棒了 dataframe1:Pandas Python-基于多个条件提取行。包括数据示例,python,dataframe,Python,Dataframe,我正在尝试根据条件将行从dataframe1提取到dataframe2,但我正在努力,有人能帮我吗?那太棒了 dataframe1: df1 = pd.DataFrame([[1001, 'democrat',0.23],[1001, 'republican',0.7],[1001, 'others',0.07],[1003, 'democrat',0.33],[1003, 'republican',0.44],[1003, 'others',0.23]], columns=['Fips_cod
df1 = pd.DataFrame([[1001, 'democrat',0.23],[1001, 'republican',0.7],[1001, 'others',0.07],[1003, 'democrat',0.33],[1003, 'republican',0.44],[1003, 'others',0.23]], columns=['Fips_code', 'Partisan', 'Vote_Pct'])
数据框架2:
df2 = pd.DataFrame([[1001],[1003], [1005]], columns=['Fips_code'])
根据fips代码条件,我想在dataframe2中添加三列,如下所示(“民主党人投票权”、“共和党人投票权”、“其他人投票权”)
期望输出:
df2 = pd.DataFrame([[1001,0.23,0.7,0.07],[1003,0.33,0.44,0.23], [1005, NA, NA, NA]], columns=['Fips_code','democrat_vote_pct','republican_vote_pct','others_vote_pct'])
请帮帮我。你可以试试这样的东西:
_df2 = df1.pivot_table(values='Vote_Pct', index='Fips_code', columns='Partisan')
然后:
result = df2.merge(_df2, on='Fips_code', how='left')
这会给你想要的:
Fips_code democrat others republican
0 1001 0.23 0.07 0.70
1 1003 0.33 0.23 0.44
2 1005 NaN NaN NaN
如果希望列具有不同的名称,只需为其指定一个.rename()
我遇到了一个错误,但我可以处理使用透视表的想法。谢谢
new_cols = {'democrat': 'democrat_pct_votes',
'others': 'others_pct_votes',
'republican': 'republican_pct_votes'}
df2.rename(new_cols, axis=1, inplace=True)