3

pandas的多表连接

 2 years ago
source link: http://www.justdopython.com/2022/09/04/python-joint/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

pandas的多表连接

2022-09-04

| Python

大家好,我是派森酱。

上次介绍了pandas的两表连接merge技能,有的酱友留言说那么点数据用excel就挺快,在这里说明一下,文章内容只是用部分代码来介绍功能的用法和最后的结果显示,不是真的用几个G的文件来展示,也展示不过来的。

熟悉了功能怎么用,就可以用自己的数据来操作了。

merge可以匹配两表的内容,但是merge只能连接两个表,不能多表连接,这次说说能用于多表连接的功能concat

还是用上次的数据,这次多加了一个DataFrame,用于显示结果。

初始化数据

python
import pandas as pd

df1 = pd.DataFrame({
    '姓名': ['张三', '李四', '王五', '刘六', '齐四'],
    '号码': ['123', '456', '789', '987', '654']
})

df2 = pd.DataFrame({
    '姓名': ['张三', '张三', '张三', '李四', '李四', '李四', '李四', '王五', '王五', '刘玉', '胡军', '刘玉', '刘六', '刘六', '刘六', '刘六', '刘克', '刘玉', '齐七', '齐七', '齐七', '齐七', '冯亮', '刘玉', '王云'],

    '号码': ['123', '456', '789', '123', '123', '456', '456', '456', '456', '456', '741', '741', '741', '741', '741', '789', '789', '789', '789', '789', '852', '852', '852', '852', '852'],

    '日期': ['2022-03-13', '2022-03-06', '2022-01-30', '2022-01-04', '2022-02-26', '2022-03-26', '2022-03-06', '2022-01-30', '2022-01-29', '2022-03-13', '2022-03-06', '2022-02-19', '2022-02-04', '2022-03-10', '2022-04-19', '2022-03-10', '2022-01-29', '2022-02-19', '2022-03-06', '2022-03-26', '2022-01-04', '2022-02-04', '2022-04-19', '2022-02-26', '2022-03-06'],

    '方案': ['G1012', 'G1022', 'G1002', 'G1007', 'G1017', 'G1023', 'G1018', 'G1003', 'G1008', 'G1013', 'G1020', 'G1015', 'G1010', 'G1005', 'G1025', 'G1004', 'G1009', 'G1014', 'G1019', 'G1024', 'G1006', 'G1011', 'G1026', 'G1016', 'G1021']
})

df3 = pd.DataFrame({
    '姓名': ['张三', '李四', '王五', '刘六', '齐四'],
    '号码': ['123', '456', '789', '987', '654'],
    '年龄': ['25', '36', '41', '12', '54']
})

concat是一个轴向连接的功能,可以沿着一条轴将多个表对象堆叠到一起:how的模式是outer

axis=0是上下拼接,列重复的会自动合并,axis=1是左右拼接,行或索引重复的会自动合并

先连接两个表:
df = pd.concat([df1, df2], axis=0)

两个表的重复列名自动合并了,缺失的值为NaN

连接三个表:
df = pd.concat([df1, df2, df3], axis=0)

同时增加了另一个表的内容和增加了一列,缺失值同样为NaN

直接拼接三个表:
df = pd.concat([df1, df2, df3], axis=1)

这次是在右边拼接的,行是按内容行最多的来算,其它的内容为空,列一直在增加,是把三个表的列都拼接上了。

mergeconcat的表连接,都有各自的特点,我们需要按自己所需要的结果去用,想匹配内容的,就用merge,想全部连接到一起的,就用concat

Python Geek Tech wechat
欢迎订阅 Python 技术,这里分享关于 Python 的一切。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK