使用加入在大熊猫中加入2个数据框

发布于 2025-02-01 03:05:46 字数 433 浏览 3 评论 0原文

我有两个数据帧DF1和DF2

DF1

id     name
ada1  mike
ad23  tom
cev2  tim

DF2

 id   month.   sales
 ada1. 1/11.    23
 ada1. 4/11.    34
 ad23. 3/12.    34
 cev2. 4/11.    32

我需要:

 id   month.   sales name
 ada1. 1/11.    23.  mike
 ada1. 4/11.    34.  mike
 ad23. 3/12.    34.  tom
 cev2. 4/11.    32.  tim

我在左联接或右JOIN之间被击中,我应该使用什么。

I have two data frames df1 and df2

df1

id     name
ada1  mike
ad23  tom
cev2  tim

df2

 id   month.   sales
 ada1. 1/11.    23
 ada1. 4/11.    34
 ad23. 3/12.    34
 cev2. 4/11.    32

I need :

 id   month.   sales name
 ada1. 1/11.    23.  mike
 ada1. 4/11.    34.  mike
 ad23. 3/12.    34.  tom
 cev2. 4/11.    32.  tim

I am struck between left join or right join, what should i use.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凑诗 2025-02-08 03:05:46

使用pd.merge

>>> df2.merge(df1, on='id', how='left')

     id month  sales  name
0  ada1  1/11     23  mike
1  ada1  4/11     34  mike
2  ad23  3/12     34   tom
3  cev2  4/11     32   tim

Use pd.merge:

>>> df2.merge(df1, on='id', how='left')

     id month  sales  name
0  ada1  1/11     23  mike
1  ada1  4/11     34  mike
2  ad23  3/12     34   tom
3  cev2  4/11     32   tim
双马尾 2025-02-08 03:05:46

使用映射,因为您将在一列上加入\合并并返回一列。

df2['name'] = df2['id'].map(df1.set_index('id')['name'])

地图将胜过加入\合并。

Use map, since you are joining\merging on one column and returning one column.

df2['name'] = df2['id'].map(df1.set_index('id')['name'])

Map will outperform join\merge.

燕归巢 2025-02-08 03:05:46

提供两种可以根据问题集提供帮助的方法

import pandas as pd

# retain df2 and merge df1 use 'leftjoin'
df2.merge(df1, on='id', how='left')

# Full Join, also known as Full Outer Join, returns all those records which 
 either have a match in the left or right dataframe

pd.merge(df2,df1,on='id',how='outer',indicator=True)

Providing two methods that can help based on problem set

import pandas as pd

# retain df2 and merge df1 use 'leftjoin'
df2.merge(df1, on='id', how='left')

# Full Join, also known as Full Outer Join, returns all those records which 
 either have a match in the left or right dataframe

pd.merge(df2,df1,on='id',how='outer',indicator=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文