簡體   English   中英

如何檢查一列中的值是否可以包含多於另一列中的值

[英]How to check if a value in one column can contain more than value in another column

我有以下 dataframe:

df = pd.DataFrame()
df['id'] = [1, 1, 2, 2]
df['col1'] = [10, 10, 20, 20]
df['col2'] = [100, 200, 50, 50]
df['col3'] = [1, 2, 3, 4]

目標

從這個 dataframe 中,我想返回 dataframe 的一部分,其中col1中的值可以在col2中具有特定ID多個值 在這種情況下,id '1' 在 col1 中的值為 10,在 col2 中為 100。 由於 id '1' 在第二行 col1 中的值也為 10,因此 col2 中的值也應為 100。此 id 不是這種情況,但是 ID '2' 是這種情況。 它應該雙向工作,所以 col1 和 col2 的值應該只是相互一致的 ID。 第 3 列包含對匹配不重要但應包含在 dataframe 中的其他值。

所需 output

dataframe 中列的值匹配的部分。

df = pd.DataFrame()
df['id'] = [1, 1]
df['col1'] = [10, 10]
df['col2'] = [100, 200]
df['col3'] = [1, 2]

您 groupby 並檢查 col1 中每個值的唯一值的數量,如果它是 1,則保留它:

df = df[(df.groupby(['id', 'col1'])['col2'].transform(lambda x: x.nunique()!=1))]
print(df)

id  col1  col2
2    20    50
2    20    50

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM