二、merge:通过键拼接列

类似于关系型数据库的连接方式,可以根据一个或多个键将不同的DatFrame连接起来。

该函数的典型应用场景是,针对同一个主键存在两张不同字段的表,根据主键整合到一张表里面。

merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True,
suffixes=('_x', '_y'), copy=True, indicator=False)

参数介绍:

left和right:两个不同的DataFrame;

how:连接方式,有inner、left、right、outer,默认为inner;

on:指的是用于连接的列索引名称,必须存在于左右两个DataFrame中,如果没有指定且其他参数也没有指定,则以两个DataFrame列名交集作为连接键;

left_on:左侧DataFrame中用于连接键的列名,这个参数左右列名不同但代表的含义相同时非常的有用;

right_on:右侧DataFrame中用于连接键的列名;

left_index:使用左侧DataFrame中的行索引作为连接键;

right_index:使用右侧DataFrame中的行索引作为连接键;

sort:默认为True,将合并的数据进行排序,设置为False可以提高性能;

suffixes:字符串值组成的元组,用于指定当左右DataFrame存在相同列名时在列名后面附加的后缀名称,默认为('_x', '_y');

copy:默认为True,总是将数据复制到数据结构中,设置为False可以提高性能;

indicator:显示合并数据中数据的来源情况

案例1

import  pandas as pd
import numpy as np
random = np.random.RandomState(0) #随机数种子,相同种子下每次运行生成的随机数相同
df1=pd.DataFrame(random.randn(3,4),columns=['a','b','c','d'])
df1

random = np.random.RandomState(0)
df2=pd.DataFrame(random.randn(2,3),columns=['b','d','a'],index=["a1","a2"])
df2

pd.merge(df1,df2)

pd.merge(df1,df2,how="outer")

案例2 默认按相同的列名键join

df3=pd.DataFrame({'key':['a','b','b'],'data1':range(3)})
df3

df4=pd.DataFrame({'key':['a','b','c'],'data2':range(3)})
df4

pd.merge(df3,df4)

案例三

df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
'value': [1, 2, 3, 5]})
df1

df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
'value': [5, 6, 7, 8]})
df2

df1.merge(df2)

Merge df1 and df2 on the lkey and rkey columns. The value columns have the default suffixes, _x and _y,

df1.merge(df2,left_on="lkey",right_on="rkey")

>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))
Traceback (most recent call last):
...
ValueError: columns overlap but no suffix specified:
Index(['value'], dtype='object')

Pandas中DataFrame数据合并、连接(concat、merge、join)之merge的更多相关文章

  1. Pandas中DataFrame数据合并、连接(concat、merge、join)之concat

    一.concat:沿着一条轴,将多个对象堆叠到一起 concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, key ...

  2. Pandas中DataFrame数据合并、连接(concat、merge、join)之join

    pandas.DataFrame.join 自己弄了很久,一看官网.感觉自己宛如智障.不要脸了,直接抄 DataFrame.join(other, on=None, how='left', lsuff ...

  3. Spark与Pandas中DataFrame对比

      Pandas Spark 工作方式 单机single machine tool,没有并行机制parallelism不支持Hadoop,处理大量数据有瓶颈 分布式并行计算框架,内建并行机制paral ...

  4. Spark与Pandas中DataFrame对比(详细)

      Pandas Spark 工作方式 单机single machine tool,没有并行机制parallelism不支持Hadoop,处理大量数据有瓶颈 分布式并行计算框架,内建并行机制paral ...

  5. 将pandas的DataFrame数据写入MySQL数据库 + sqlalchemy

    将pandas的DataFrame数据写入MySQL数据库 + sqlalchemy import pandas as pd from sqlalchemy import create_engine ...

  6. Python3 Pandas的DataFrame数据的增、删、改、查

    Python3 Pandas的DataFrame数据的增.删.改.查 一.DataFrame数据准备 增.删.改.查的方法有很多很多种,这里只展示出常用的几种. 参数inplace默认为False,只 ...

  7. Pandas中DataFrame修改列名

    Pandas中DataFrame修改列名:使用 rename df = pd.read_csv('I:/Papers/consumer/codeandpaper/TmallData/result01- ...

  8. pandas中DataFrame的ix,loc,iloc索引方式的异同

    pandas中DataFrame的ix,loc,iloc索引方式的异同 1.loc: 按照标签索引,范围包括start和end 2.iloc: 在位置上进行索引,不包括end 3.ix: 先在inde ...

  9. pandas中,dataframe 进行数据合并-pd.concat()

    ``# 通过数据框列向(左右)合并 a = pd.DataFrame(X_train) b = pd.DataFrame(y_train) # 合并数据框(合并前需要将数据设置成DataFrame格式 ...

随机推荐

  1. idea的spring整合基于xml文件配置的mybatis报Invalid bound statement (not found): com.music.dao.MusicDao.findAll的问题

    一. 题主当时就是自己尝试整合spring和mybatis的时候遇到了这个问题,当时题主只看到了用注解的方式配置的dao层,题主用的是xml文件配置的形式, 而且坑爹的是题主的两个文件的路径写的也不一 ...

  2. Compress and decompress string

    You are given a string with lower case letters only. Compress it by putting the count of the letter ...

  3. Redis(1.9)Redis主从复制

    [1]实验环境 CentOS7.5 + Redis4.0.11 架构:原生1主2从,做实验机器有限,从库双实例 主库:192.168.135.170 从库1:192.168.135.171~6379 ...

  4. 正则re模块--入门

    本文来源:https://www.cnblogs.com/dyfblog/p/5880728.html 对字符串操作 1.应用: 当我们爬取的东西在js文件中,比如我爬今日头条美女的图片时,它的图片u ...

  5. spring boot 项目开发常用目录结构

    在spring boot开发中一些常用的目录划分 转载自https://blog.csdn.net/Auntvt/article/details/80381756: 一.代码层结构 根目录:net.c ...

  6. HTML accessKey约定俗成的标准

    accessKey属性提供了键盘快捷键 例: <a href="index.html" accessKey="1">Home</a> 这 ...

  7. Python安装及环境变量

    针对windows操作系统 1.下载安装包,python官网下载(https://www.python.org/) python3.7.4:下载https://www.python.org/downl ...

  8. Python 3.8.0 正式版发布,新特性初体验 全面介绍

    Python 3.8.0 正式版发布,新特性初体验 北京时间 10 月 15 日,Python 官方发布了 3.8.0 正式版,该版本较 3.7 版本再次带来了多个非常实用的新特性. 赋值表达式 PE ...

  9. Censoring(栈+KMP)

    # 10048. 「一本通 2.2 练习 4」Censoring [题目描述] 给出两个字符串 $S$ 和 $T$,每次从前往后找到 $S$ 的一个子串 $A=T$ 并将其删除,空缺位依次向前补齐,重 ...

  10. C Looooops

    看了半天的同余 扩展欧几里得 练练手 C Looooops Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 27079   A ...