简体   繁体   English

如果另一列具有相同的值,则检查一列是否具有相同的值

[英]Checking if a column has the same values if the other column has the same value

I have two string columns in a Pandas dataframe.我在 Pandas dataframe 中有两个字符串列。 Column1 has thousands of different values, but column2 has one of five strings, say A, B, C, D, and E. Column1 有数千个不同的值,但 column2 有五个字符串之一,例如 A、B、C、D 和 E。

What I would like to check is if column2 has the same value if the values are same in column1 and identify the index of the row if they are diffent.我想检查的是,如果 column1 中的值相同,则 column2 是否具有相同的值,如果它们不同,则标识行的索引。

idx  col1  col2
1    X     A
2    Y     B
3    Y     B
4    X     A
5    Z     C
6    X     B

In the above, rows 2 and 3 has the same values in column1 and the values in column are the same.在上面,第 2 行和第 3 行在 column1 中具有相同的值,并且在 column 中的值相同。 So it is okay.所以没关系。 For rows 1, 4, and 6, it is commonly X in column A but the values in column2 are different (A, A, and B).对于第 1、4 和 6 行,A 列中通常为 X,但第 2 列中的值不同(A、A 和 B)。

I need to check the Pandas dataframe meets this requirement, and identify the rows 1, 4, and 6 or the value X if there is one.我需要检查 Pandas dataframe 是否满足此要求,并确定第 1、4 和 6 行或值 X(如果有)。

Use GroupBy.transform with DataFrameGroupBy.nunique for get rows not number of unique values per groups equal 1 :使用GroupBy.transformDataFrameGroupBy.nunique获取行而不是每组唯一值的数量等于1

df1 = df[df.groupby('col1')['col2'].transform('nunique').ne(1)]
print (df1)
   idx col1 col2
0    1    X    A
3    4    X    A
5    6    X    B

Or for get values of column col1 use DataFrameGroupBy.nunique with filter indices of Series :或者为了获取col1列的值,使用DataFrameGroupBy.nuniqueSeries的过滤器索引:

s = df.groupby('col1')['col2'].nunique()
vals = s.index[s.ne(1)].tolist()
print (vals)
['X']

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

相关问题 由于来自不同行的文本值组合在其他 pandas 列中具有相同值,因此创建新的 pandas 行 - Create new pandas row as a result of combination of text values from different rows which has same value in other pandas column 根据 pandas 中的其他列值合并具有相同列值的行 - Merge row with a same column value based on other column values in pandas 仅当另一列具有相同的值时,如何减去具有不同长度的两列 - How to subtract two columns with different length only if other column has the same value 从其他数据框具有相同键的1个数据框更新列 - Updating a column from 1 Dataframe where other Dataframe has same keys 计算 Pandas 中具有相同列值的行的平均值 - Compute mean value of rows that has the same column value in Pandas 使用具有相同列的数据创建新列 - Create new column with data that has same column 在 pandas 索引中旋转,并且列具有相同的列 - pivotting in pandas index and column has same column 从 dataframe 计算百分比,它在“值”列中具有相同的 id 和多个值 - calculate percentage from a dataframe which has same id and multiple values in 'value' column 如何添加具有相同值的列 - How can i add a column that has the same value 同时创建长度与数据中最长列相同的列 - Create a column that has the same length of the longest column in the data at the same time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM