Alex_ban
Alex_ban

Reputation: 321

How to count the frequency of values occur for a particular row across all columns

Suppose I have a data frame with four columns and part of this is like:

C1 C2 C3 C4
60 60 60 60
59 59 58 58
0  0  0  0
12 13 13 11 

Now i want to create four columns each corresponding to the frequency of each values considering other three columns like the columns will look like:

F1 F2 F3 F4
4  4  4  4
2  2  2  2
2  2  2  2
1  2  2  1

In the cell 1,1 the value is 4 because the value 60 appears in all the columns for the particular rows. In cell 4,1 the value is 1 as 12 appears in no other columns for the particular row. I need to calculate and add the features F1,F2,F3,F4 in the pandas data frame.

Upvotes: 1

Views: 604

Answers (1)

jezrael
jezrael

Reputation: 863031

Use apply axis=1 for process by rows with map by frequencies by value_counts:

df = df.apply(lambda x: x.map(x.value_counts()),axis=1)
print (df)
   C1  C2  C3  C4
0   4   4   4   4
1   2   2   2   2
2   4   4   4   4
3   1   2   2   1

Upvotes: 2

Related Questions