How to compute the percentage of values based on multiple columns

  • Python
  • Thread starter msn009
  • Start date
  • Tags
    python
  • #1
53
6
I have a dataframe as shown in the picture and what I am trying to do is to calculate the number of occurrences based on the values in 2 columns and then calculate the percentage of the occurrences. I have tried the following code but it gives me a zero value in the end and i don't know why.

Code:
count_a2_x = (df['a1'].str.contains('b') & df['a2'].str.contains('x')).value_counts()[True]
count_a2_y = (df['a1'].str.contains('b') & df['a2'].str.contains('y')).value_counts()[True]
acc  = float(count_a2_x/ (count_a2_x + count_a2_y))
the expected output should be 3/6 = 0.5
 

Attachments

Answers and Replies

  • #2
34,687
6,394
I have a dataframe as shown in the picture and what I am trying to do is to calculate the number of occurrences based on the values in 2 columns and then calculate the percentage of the occurrences. I have tried the following code but it gives me a zero value in the end and i don't know why.

Code:
count_a2_x = (df['a1'].str.contains('b') & df['a2'].str.contains('x')).value_counts()[True]
count_a2_y = (df['a1'].str.contains('b') & df['a2'].str.contains('y')).value_counts()[True]
acc  = float(count_a2_x/ (count_a2_x + count_a2_y))
the expected output should be 3/6 = 0.5
Use and instead of &. The & operator is the bitwise and operator.
 
  • #3
53
6
when i changed it to and it gave me this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

and I tried now to add float and it seems to work when float is assigned in the beginning.

Code:
count_a2_x = float((df['a1'].str.contains('b') & df['a2'].str.contains('x')).value_counts()[True])
count_a2_y = float((df['a1'].str.contains('b') & df['a2'].str.contains('y')).value_counts()[True])
acc  = count_a2_x/ (count_a2_x + count_a2_y)
 

Related Threads on How to compute the percentage of values based on multiple columns

  • Last Post
Replies
1
Views
811
Replies
18
Views
4K
Replies
8
Views
3K
Replies
14
Views
2K
Replies
7
Views
5K
Replies
1
Views
675
Replies
9
Views
782
  • Last Post
Replies
2
Views
794
Top