pandas学习(五)

pandas学习五

import pandas as pd
import numpy as np
left=pd.DataFrame({
     'key':['a','b','c'],
                  'A':['a1','b1','c1'],
                  'key2':['a3','b3','c3']})
right=pd.DataFrame({
     'key':['a','b','c'],
                  'B':['a2','b2','c2'],
                   'key2':['a3','b3','c3']})

merge合并

pd.merge(left,right,on='key')#类似数据库
key A key2_x B key2_y
0 a a1 a3 a2 a3
1 b b1 b3 b2 b3
2 c c1 c3 c2 c3
#how=['left','right','inner','outer'] 类似数据库的四种连接,默认是inner 内连接  indicator可以显示出连接方式
pd.merge(left,right,on=['key','key2'],how='inner',indicator=True)
key A key2 B _merge
0 a a1 a3 a2 both
1 b b1 b3 b2 both
2 c c1 c3 c2 both

merge index合并

#初始数据
left=pd.DataFrame({
     'key':['a','b','c'],
                  'A':['a1','b1','c1']},index=['k1','k2','k3'])
right=pd.DataFrame({
     'key':['a','b','c'],
                  'A':['a2','b2','c2']},index=['k1','k2','k3'])
pd.merge(left,right,left_index=True,right_index=True,how='outer')
key_x A_x key_y A_y
k1 a a1 a a2
k2 b b1 b b2
k3 c c1 c c2
pd.merge(left,right,on='key',suffixes=['test1','test2'])
key Atest1 Atest2
0 a a1 a2
1 b b1 b2
2 c c1 c2

你可能感兴趣的:(Python,数据分析,机器学习)