1

I have a following data frame,

df1=
mac           gw_mac        ibeaconMajor  ibeaconMinor     
ac233f264920  ac233fc015f6  [1, 0, 1]        [1, 0] 
ac233f26492b  ac233fc015f6  [0, 0, 0]        [0, 0] 
ac233f264933  ac233fc015f6  [0, 1, 1]        [0, 2] 

If all the values in a list(from the columns "ibeaconMajor" & "ibeaconMinor") is "0" it should return as "0" or else it should return frequently occurred non-zero values from a list as like below,

df1=
mac           gw_mac        ibeaconMajor  ibeaconMinor     
ac233f264920  ac233fc015f6  1             1 
ac233f26492b  ac233fc015f6  0             0 
ac233f264933  ac233fc015f6  1             2 

1 Answer 1

1

Idea is use DataFrame.applymap for elementwise apply lambda function - first remve 0 values in list comprehension, get top values by Counter and add next with iter for possible add 0 if all 0 values - here in tuple for possible select first value of tuples:

from collections import Counter

cols = ['ibeaconMajor','ibeaconMinor']

f = lambda x: next(iter(Counter([y for y in x if y != 0]).most_common(1)), (0,))[0]
#alternative
#f = lambda x: next(iter(Counter(filter(lambda y: y != 0, x)).most_common(1)), (0,))[0]
df[cols] = df[cols].applymap(f)

print (df)
            mac        gw_mac  ibeaconMajor  ibeaconMinor
0  ac233f264920  ac233fc015f6             1             1
1  ac233f26492b  ac233fc015f6             0             0
2  ac233f264933  ac233fc015f6             1             2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.