[英]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.transform
和DataFrameGroupBy.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.nunique
和Series
的过滤器索引:
s = df.groupby('col1')['col2'].nunique()
vals = s.index[s.ne(1)].tolist()
print (vals)
['X']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.