![](/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.