user3285817 user3285817 - 1 month ago 8
Python Question

Python Pandas Using dataframe.stack().value_counts() -- How to get values of counted objects?

I have a data frame that in which every row represents a day of the week, and every column represents the serial number of an internet-connected device that failed to communicate with the server on that day.

I am trying to get a Series of serial numbers that have failed to communicate for a full week.

The code block:

counts = df.stack().value_counts()
seven_day = counts[counts == 7]
for a in seven_day:
print(a)


The problem is that nothing is printed. What I want is a list of the serial numbers, and not the counts themselves.

This question is a follow-up from:
Python Pandas -- Determine if Values in Column 0 Are Repeated in Each Subsequent Column

Answer

value_counts returns a Series with the values as the index and the counts as the values, so you want to iterate over the index:

counts = df.stack().value_counts()
seven_day = counts[counts == 7]
for a in seven_day.index:
    print(a)

should work

Comments