![](/img/trans.png)
[英]Create new pandas row as a result of combination of text values from different rows which has same value in other pandas column
[英]Checking if a column has the same values if the other column has the same value
我在 Pandas dataframe 中有两个字符串列。 Column1 有数千个不同的值,但 column2 有五个字符串之一,例如 A、B、C、D 和 E。
我想检查的是,如果 column1 中的值相同,则 column2 是否具有相同的值,如果它们不同,则标识行的索引。
idx col1 col2
1 X A
2 Y B
3 Y B
4 X A
5 Z C
6 X B
在上面,第 2 行和第 3 行在 column1 中具有相同的值,并且在 column 中的值相同。 所以没关系。 对于第 1、4 和 6 行,A 列中通常为 X,但第 2 列中的值不同(A、A 和 B)。
我需要检查 Pandas dataframe 是否满足此要求,并确定第 1、4 和 6 行或值 X(如果有)。
使用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
或者为了获取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.