首页  

pandas dataframe merge     所属分类 python 浏览量 115
Series 有 join 方法,根据索引进行连接
DataFrame  没有 join 方法, 可通过 merge 和 concat 实现 

merge  用于基于一个或多个键将两个 DataFrame 连接起来 ,类似于 SQL 中的 JOIN 

import pandas as pd  
  
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': [1, 2, 3, 4]})  
df2 = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': [5, 6, 7, 8]})  
  
merged_df = pd.merge(df1, df2, on='key', how='left')
print(merged_df)

how='left' 表示进行左连接,保留 df1 中的所有键,即使它们在 df2 中没有匹配项。



df3 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})  
df4 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})  
concatenated_df = pd.concat([df3, df4], ignore_index=True)
print(concatenated_df)

ignore_index=True 表示重置索引


append 不是真正的“连接”方法,将一个 DataFrame 添加到另一个 DataFrame 的末尾

df5 = df3.append(df4, ignore_index=True)

这与使用 concat 进行垂直连接(沿着行)是等效的

FutureWarning: 
The frame.append method is deprecated and will be removed from pandas in a future version. 
Use pandas.concat instead.

上一篇     下一篇
大模型简介

国内大模型

python pandas 使用技巧

pandas pivot_table 数据透视表

numpy 实用代码

信贷风控业务知识-001-信贷业务介绍-信贷基础指标和风险指标