Skip to content
Advertisement

Identify number of occurrence of any combination of equal elements in DataFrame

I have a mock dataframe, df1 with 6 columns and 5 rows, i.e., with shape (5 x 6).

Each column represents the price of an area, and rows are time.

JavaScript

Now, I want to identify – in each row – the areas with the same price as the first column “DK1”, and then being able to sum up how often any combination of columns are equal, meaning that my desired output for this would be:

JavaScript

Preferably, the solution should be applicable to any sized DataFrame. I started trying with the .apply() method, but couldn’t quite get started. Hope you can help.

Advertisement

Answer

Compare DataFrame by first column by DataFrame.eq, then use matrix multiplication by DataFrame.dot with columns names with separator and last count with Series.value_counts and convert to DataFrame:

JavaScript

EDIT: For groups is possible create dictionary by all values and then call replace:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement