Populate the array with condition on dataframe column

Viewed 56

I want to count the frequency of rows from a column and with the frequency greater than 3, I want to populate an array with those rows.

For example:

402       Sony
403       Sony
404       Sony
405        ZTE
406        ZTE
407        ZTE
408        ZTE
409        ZTE

Desired array:

[
"ZTE",
"ZTE",
"ZTE",
"ZTE",
"ZTE"]
1 Answers

Use collections.Counter() to get the occurance frequency. So assuming the data you provided comes from the file test.txt:

import collections
itemList = []
with open("test.txt", 'r') as f:
    for line in f:
        itemList.append(line.split()[1])
result = collections.Counter(itemList)
print(result)
#get the n most repeated values in a list of tuples:
n = 1
print(result.most_common(n))

Will input

402       Sony
403       Sony
404       Sony
405        ZTE
406        ZTE
407        ZTE
408        ZTE
409        ZTE

And output:

Counter({'ZTE': 5, 'Sony': 3})
[('ZTE', 5)]
Related