Pandas:将一个数据框的特定列连接到另一个数据框

4

I have 2 following data frames in pandas:

movies

+---+------------------------------+--------------+-----------+
|   | movie title                  | genre        | tconst    |
+---+------------------------------+--------------+-----------+
| 0 | Edison Kinetoscopic Record   | Documentary  | tt0000008 |
+---+------------------------------+--------------+-----------+
| 1 | La sortie des usines Lumière | Documentary  | tt0000010 |
+---+------------------------------+--------------+-----------+
| 2 | The Arrival of a Train       | Documentary  | tt0000012 |
+---+------------------------------+--------------+-----------+
| 3 | The Oxford and Cambridge     | NaN          | tt0000025 |
+---+------------------------------+--------------+-----------+
| 4 | Le manoir du diable          | Short|Horror | tt0000091 |
+---+------------------------------+--------------+-----------+

机组人员

+---+-----------+-----------+---------+------+
|   | tconst    | directors | writers | year |
+---+-----------+-----------+---------+------+
| 0 | tt0000001 | nm0005690 | \N      | 2001 |
+---+-----------+-----------+---------+------+
| 1 | tt0000002 | nm0721526 | \N      | 2002 |
+---+-----------+-----------+---------+------+
| 2 | tt0000003 | nm0721526 | \N      | 2003 |
+---+-----------+-----------+---------+------+
| 3 | tt0000004 | nm0721526 | \N      | 2004 |
+---+-----------+-----------+---------+------+
| 4 | tt0000005 | nm0005690 | \N      | 2005 |
+---+-----------+-----------+---------+------+

我该如何创建一个新的数据框,将 directorsyear 列与 movies 数据框(使用 tconst 列)进行连接?

你能否重新格式化帖子以正确显示你的数据框?这样做不仅易于跟踪,也有助于别人更好地帮助你。 - d_kennetz
1
抱歉,我很确定我做的一切都是正确的,但表格仍然看起来很糟糕。 - Pinky the mouse
1
下面是很好的答案! - d_kennetz
1个回答

20

尝试:

pd.merge(movies, crew[["tconst", "directors", "year"]], on="tconst", how="left")

参数on告诉函数您要根据键tconst合并,参数how告诉函数如何处理两个DataFrame之间没有交集的行。


1
谢谢!正是我在寻找的。 - Pinky the mouse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接