簡體   English   中英

如何檢查熊貓數據框中列中的元素是否在該列中出現兩次或兩次以上

[英]How to check if an element in a column in a pandas data frame occurs twice or more than twice in that column

我有以下熊貓數據框。 我正在嘗試編寫一個代碼來檢查“to_address”列的元素是否在該列中出現兩次或兩次以上。

在此處輸入圖像描述

我正在以這樣一種方式編寫代碼,即如果列中有匹配項,那么它將在后續迭代中被排除在外,這樣就不會出現重復的情況。 為此,我添加了一個“flag_column”,填充為 1。除非發生匹配,否則該值將保持為 1。如果發生匹配,“flag_column”的該行中的值將更改為零。 如果在隨后的迭代中遇到具有“flag_column”==0 的行,則將跳過計算。

n=0
m=0
for i in range(df_containing_nft.shape[0]): # or len(df_containing_nft)
    Text_to_search=df_containing_nft.iat[i,2]
    if(df_containing_nft.iat[i,3]==0):
        m=m+1
        continue
    for j in range(i+1, df_containing_nft.shape[0]):        
        if (df_containing_nft.iat[j,2]==Text_to_search):            
            n=n+1            
            print(Text_to_search)
            print(df_containing_nft.iloc[i])
            print(df_containing_nft.iloc[j])
            df_containing_nft.at[j, 3] = 0 # Setting flag equal to zero. Row already visited           
            print("------------------------------------------------------------------")
            
print(n)
print(m)

我面臨的問題是沒有。 結果結果的數量約為 67500,大約是數據框中存在的行數 3177 的 20 倍(我通過打印 n 得出),這很奇怪。 此外,設置 flag ==0 並跳過計算的想法似乎不起作用,因為 m 結果為零。

我是否在計算中犯了一些錯誤,或者如果這確實是得出結果的正確方法,我無法理解。 請幫我解決我的問題。

如果在您的數據中找到重復的行,則重復的方法返回 True。 波浪號返回相反的結果 (False)。 應用 int 將使其成為 0 和 1 值

df['flag_column'] = (~df['to_address'].duplicated()).apply(int)

此代碼根據列從 pandas 數據框中刪除重復項:

import pandas as pd

# Replace this with your dataframe
df = pd.DataFrame([{"name": "apple",  "fruit": True,  "vegetable": False, "value": 1},
                   {"name": "banana", "fruit": True,  "vegetable": False, "value": 2},
                   {"name": "carrot", "fruit": False, "vegetable": True, "value": 1}])

print(df) # My dataframe
#      name  fruit  vegetable  value
# 0   apple   True      False      1
# 1  banana   True      False      2
# 2  carrot  False       True      1

df = df.drop_duplicates(subset="value") # Change column name to yours

# Print new dataframe
print(df)
#      name  fruit  vegetable  value
# 0   apple   True      False      1
# 1  banana   True      False      2

暫無
暫無

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

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