简体   繁体   English

在 Pandas 中,如何测试给定唯一 ID 的两个数据帧中是否存在一个值?

[英]In Pandas how can I test whether a value exists in two dataframes given a unique ID?

I have two dataframes like this where both frames can have multiple entries for each ID:我有两个这样的数据帧,其中两个帧都可以为每个 ID 包含多个条目:

The first dataframe df1:第一个 dataframe df1:

ID ID Amount数量
101 101 $30 30 美元
102 102 $300 300 美元
101 101 $35 35 美元
103 103 $10 10 美元
104 104 $220 220 美元
103 103 $370 370 美元
101 101 $500 500 美元
105 105 $65 65 美元

The second dataframe df2 has fewer rows but the same kind of information:第二个 dataframe df2 的行数较少但信息类型相同:

ID ID Amount数量
101 101 $35 35 美元
102 102 $2 2美元
103 103 $25 25 美元
104 104 $75 75 美元
101 101 $30 30 美元
102 102 $900 900 美元

I want to compare the dataframes and find any rows that have the same Amount for a given ID in both frames.我想比较数据帧并在两个帧中找到对于给定 ID 具有相同数量的任何行。 Here, for example, I want pandas to return ID 101 has having an entry for $30 in both frames.例如,在这里,我希望 pandas 返回 ID 101 在两个框架中都有 30 美元的条目。 Right now my intuition is to append the dataframes like so:现在我的直觉是 append 数据帧如下:

df1 = df1.append(df2,ignore_index=True)
df1[df1.duplicated()]

But I wanted to know if there's a more 'pythonic' way to do this.但我想知道是否有更“pythonic”的方式来做到这一点。 Thanks!谢谢!

So you want something like inner join between dataframes.所以你想要数据框之间的内部连接。 You can use pd.merge您可以使用pd.merge

pd.merge(df1, df2, on=["ID", "Amount"])

暂无
暂无

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

相关问题 在具有唯一行 ID 列的 Python Pandas DataFrames 中,如何在给定行 ID 的情况下查找列值? - In Python Pandas DataFrames with column of unique row IDs, how to find column value given row ID? Pandas 如何在不删除唯一值的情况下映射两个数据框? - Pandas How to mapping two dataframes without remove unique value? 如果特定列存在于具有 Pandas 的两个 DataFrame 中,则替换列值 - Substituting column value if particular column exists in two DataFrames with Pandas 如何在熊猫中将两个具有不同列标签的数据框相乘? - How can I multiply two dataframes with different column labels in pandas? 如何根据 Pandas 中的一列列表组合两个数据帧 - How can I combine two dataframes based on a column of lists in Pandas 如何按单元格添加两个 pandas.DataFrames? - How can I add two pandas.DataFrames cellwise? 如何按值组合两个熊猫数据框 - How to combine two pandas dataframes value by value 如何“行绑定”具有不同列的两个熊猫数据框? - How can I 'row bind' two pandas dataframes with different columns? 使用两个数据框如何比较查找值作为 substring 在另一个 dataframe 的列中创建一个新列,如果匹配存在 - Using two dataframes how can I compare a lookup value as a substring in the column in another dataframe to create a new column if the match exists 如何找到关键列上两个数据帧之间的差异并从两个数据帧中删除唯一记录 - How can i find the difference between two dataframes on key column and remove the unique records from both dataframes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM