本文介绍了如何在没有密钥的情况下实现SQL外连接的 pandas 等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL中,您可以在没有键的情况下联接两个表,以便两个表的所有记录彼此合并.如果pandas.concat()pandas.merge()或某些其他pandas语法支持此功能,则可以帮助我解决我要解决的问题的第一步.我在帮助文档中找到了一个外部联接选项,但是找不到确切的语法来执行我想要的操作(联接所有没有键的记录).

In SQL, you can join two tables without a key so that all records of both tables merge with each other. If pandas.concat() or pandas.merge() or some other pandas syntax supported this, it could help me with one step of a problem I am trying to solve. I found an outer join option on the help documentation, but I could not find an exact syntax to do what I wanted (join all records without a key).

为了更好地解释这一点,

To explain this a little better:

import pandas as pd

lunchmenupairs2 = [["pizza", "italian"],["lasagna", "italian"],["orange", "fruit"]]
teamcuisinepreferences2 = [["ian", "*"]]

lunchLabels = ["Food", "Type"]
teamLabels = ["Person", "Type"]

df1 = pd.DataFrame.from_records(lunchmenupairs2, columns=lunchLabels)
df2 = pd.DataFrame.from_records(teamcuisinepreferences2, columns=teamLabels)

print(df1)
print(df2)

输出这些表:

      Food     Type
0    pizza  italian
1  lasagna  italian
2   orange    fruit

  Person     Type
0    ian        *

我希望合并的最终结果是:

I want the final result of the merge to be:

  Person     Type Food     Type
0  ian        *   pizza     italian
1  ian        *   lasagna   italian
2  ian        *   orange    fruit

然后,我可以轻松删除不需要的列,并转到我正在处理的代码中的下一步.这不起作用:

Then I can easily drop the columns I don't want and move to the next step in the code I am working on. This doesn't work:

merged_data = pd.merge(left=df2,right=df1, how='outer')

是否可以进行这种类型的DataFrame合并?

Is there a way to do this type of DataFrame merging?

推荐答案

您可以为两个dfs添加一个具有恒定值的列,

You can add a column to both dfs with a constant value,

>>>df1['joincol'] = 1
>>>df2['joincol'] = 1
>>>pd.merge(left=df2,right=df1, on='joincol', how='outer')
  Person Type_x  joincol     Food   Type_y
0    ian      *        1    pizza  italian
1    ian      *        1  lasagna  italian
2    ian      *        1   orange    fruit

然后在删除其他不需要的列后将其删除.

then delete it afterward when you remove your other undesired columns.

这篇关于如何在没有密钥的情况下实现SQL外连接的 pandas 等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:15