您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python panda:返回常见行的索引

python panda:返回常见行的索引

不需要带有连接值的新列,认情况下,通过两个列进行内部合并,如果需要,则使用df2.indexadd值进行合并reset_index

df1 = pd.DataFrame({'col1':['cx','cx','cx2'], 'col2':[1,4,12]})
df2 = pd.DataFrame({'col1':['cx','cx','cx','cx','cx2','cx2'], 'col2':[1,3,5,10,12,12]})

df3 = pd.merge(df1,df2.reset_index(), on = ['col1','col2'])
print (df3)
  col1 col2  index
0   cx    1      0
1  cx2   12      4
2  cx2   12      5

对于两个索引都需要:

df4 = pd.merge(df1.reset_index(),df2.reset_index(), on = ['col1','col2'])
print (df4)

   index_x col1  col2  index_y
0        0   cx     1        0
1        2  cx2    12        4
2        2  cx2    12        5

仅对于两个DataFrame的交集:

df5 = pd.merge(df1,df2, on = ['col1','col2'])
#if 2 column DataFrame   
#df5 = pd.merge(df1,df2)
print (df5)

  col1  col2
0   cx     1
1  cx2    12
2  cx2    12
python 2022/1/1 18:50:10 有351人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶