我正在尝试根据条件从 dataframe1 到 dataframe2 提取行,但我很挣扎,有人可以帮助我吗?那就太棒了。数据框1: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 中,如下所示 ('democrat_vote_pct','republican_vote_pct','others_vote_pct')。期望出: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'])请帮我..
1 回答
HUX布斯
TA贡献1876条经验 获得超6个赞
你可以尝试这样的事情:
_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)
添加回答
举报
0/150
提交
取消