簡體   English   中英

帶有if語句的python dataframe布爾值

[英]python dataframe boolean values with if statement

我想讓if語句顯示所有重復的REF_INT我試過這個:

(df_picru['REF_INT'].value_counts()==1)

並且它向我顯示了所有值的真或假,但我不想做這樣的事情:

if (df_picru['REF_INT'].value_counts()==1)
print "df_picru['REF_INT']"
In [28]: df_picru['new'] = \
             df_picru['REF_INT'].duplicated(keep=False) \
                     .map({True:'duplicates',False:'unique'})

In [29]: df_picru
Out[29]:
   REF_INT         new
0        1      unique
1        2  duplicates
2        3      unique
3        8  duplicates
4        8  duplicates
5        2  duplicates

我認為你需要duplicated布爾掩碼和新列numpy.where

mask = df_picru['REF_INT'].duplicated(keep=False)

樣品:

df_picru = pd.DataFrame({'REF_INT':[1,2,3,8,8,2]})

mask = df_picru['REF_INT'].duplicated(keep=False)
print (mask)
0    False
1     True
2    False
3     True
4     True
5     True
Name: REF_INT, dtype: bool

df_picru['new'] = np.where(mask, 'duplicates', 'unique')
print (df_picru)
   REF_INT         new
0        1      unique
1        2  duplicates
2        3      unique
3        8  duplicates
4        8  duplicates
5        2  duplicates

如果需要檢查至少一個,如果unique值需要any轉換boolean mask - array到標量TrueFalse

if mask.any():
    print ('at least one unique')
at least one unique

使用groupby的另一個解決方案

#groupby REF_INT and then count the occurrence and set as duplicate if count is greater than 1
df_picru.groupby('REF_INT').apply(lambda x: 'Duplicated' if len(x)> 1 else 'Unique')
Out[21]: 
REF_INT
1        Unique
2    Duplicated
3        Unique
8    Duplicated
dtype: object

如果你做了一個小改動,value_counts實際上可以工作:

df_picru.REF_INT.value_counts()[lambda x: x>1]
Out[31]: 
2    2
8    2
Name: REF_INT, dtype: int64

暫無
暫無

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

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