简体   繁体   English

如何连接两个具有相同列的 Pandas 数据帧,但前提是两个数据帧中的一列的值相同?

[英]How to concat two Pandas dataframes that have the same columns but only if the value of one column in both dataframes is the same?

I have two dataframes like the below:我有两个数据框,如下所示:

DF1: DF1:

col1 col1 col2 col2
22 22 yes是的
22 22 no
24 24 yes是的
22 22 no
27 27 no

DF2: DF2:

col1 col1 col2 col2
28 28 yes是的
22 22 no
29 29 yes是的
22 22 yes是的
27 27 yes是的

I want to concat both dataframes, so that I end up with the below.我想连接两个数据框,这样我就得到了下面的结果。 I don't want to join the dataframes on col1, as that doubles the number of columns.我不想加入 col1 上的数据框,因为这会使列数加倍。 I just want to combine the dataframe vertically if they share a common value on "col1."如果 dataframe 在“col1”上具有共同值,我只想垂直组合它们。 Any help on this?对此有什么帮助吗?

DF3: DF3:

col1 col1 col2 col2
22 22 yes是的
22 22 no
22 22 no
22 22 no
22 22 yes是的
27 27 no
27 27 yes是的

Let us first find the common values using set intersection then concat the required rows from df1 and df2 and optionally sort the values让我们首先使用集合交集找到公共值,然后从df1df2连接所需的行,并可选择对值进行排序

i = set(df1['col1']) & set(df2['col1'])
pd.concat([df1[df1['col1'].isin(i)], df2[df2['col1'].isin(i)]]).sort_values('col1')

   col1 col2
0    22  yes
1    22   no
3    22   no
1    22   no
3    22  yes
4    27   no
4    27  yes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pandas; 如何连接两个数据框但仅连接相同的列? - Pandas; how to concat two dataframes but only the columns that are the same? 比较 pandas 中 2 个不同数据帧中的列(两个数据帧中只有 1 列相同) - Compare a column in 2 different dataframes in pandas (only 1 column is same in both dataframes) 如何重新索引两个 pandas 数据帧中的列,以使它们具有相同的列? - How to reindex columns in two pandas dataframes so that they both have the same columns? 如何比较两个相同大小的数据框并创建一个新的数据框,而在列中没有具有相同值的行 - How to compare two dataframes of the same size and create a new one without the rows that have the same value in a column 如何仅在ID列值同时是两个数据框的情况下合并数据框,并删除ID不匹配的行? - How to concat dataframes but only where ID column value is both dataframes and delete the rows where IDs do not match? 合并两个具有相同列名但在pandas中具有不同列数的数据帧 - Merging two dataframes with same column names but different number of columns in pandas 如何组合具有相同列和数据类型的 Pandas DataFrames - How to Combine Pandas DataFrames that have the same columns and data types 合并两个具有相同列的类似数据帧 - Merge two similar dataframes that have the same columns pandas:如何在一列上合并具有相同列名的多个数据框? - pandas: How to merge multiple dataframes with same column names on one column? Pandas 数据帧 - 合并两个数据帧,但省略具有同一列的条目 - Pandas Dataframes - Combine two Dataframes but leave out entry with same column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM