在Python中使用公用列联接表/数据框

编程入门 行业动态 更新时间:2024-10-26 03:32:01
本文介绍了在Python中使用公用列联接表/数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个DataFrame:

I have two DataFrames:

df1 = ['Date_Time', 'Temp_1', 'Latitude', 'N_S', 'Longitude', 'E_W'] df2 = ['Date_Time', 'Year', 'Month', 'Day', 'Hour', 'Minute', 'Seconds']

因为您可以看到两个DataFrame都有Date_Time作为公共列.我想通过匹配Date_Time来加入这两个DataFrame.

As You can see both DataFrames have Date_Time as a common column. I want to Join these two DataFrames by matching Date_Time.

我当前的代码是:df.join(df2, on='Date_Time'),但这给出了错误.

My current code is: df.join(df2, on='Date_Time'), but this is giving an error.

推荐答案

您正在寻找 merge :

You are looking for a merge:

df1.merge(df2, on='Date_Time')

关键字与join相同,但join仅使用索引,请参见数据库样式的DataFrame合并/合并" .

The keywords are the same as for join, but join uses only the index, see "Database-style DataFrame joining/merging".

这是一个简单的例子:

import pandas as pd df1 = pd.DataFrame([[1, 2, 3]]) df2 = pd.DataFrame([[1, 7, 8],[4, 9, 9]], columns=[0, 3, 4]) In [4]: df1 Out[4]: 0 1 2 0 1 2 3 In [5]: df2 Out[5]: 0 3 4 0 1 7 8 1 4 9 9 In [6]: df1.merge(df2, on=0) Out[6]: 0 1 2 3 4 0 1 2 3 7 8 In [7]: df1.merge(df2, on=0, how='outer') Out[7]: 0 1 2 3 4 0 1 2 3 7 8 1 4 NaN NaN 9 9

如果您尝试加入一列,则会出现错误:

If you try and join on a column you get an error:

In [8]: df1.join(df2, on=0) # error! Exception: columns overlap: array([0], dtype=int64)

请参见索引" .

更多推荐

在Python中使用公用列联接表/数据框

本文发布于:2023-10-23 13:39:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!