1

I have data frame:

    Values                                      Bought
0   0,1,2,3,4,5                                 0
1   9,10,11,9,11,12,9,11                        9,12,11
2   5, 1, 1, 10, 0                              0

First qustion: I need to count how many times each number of "Values" column occured in this data frame.
For example:

 0 : 1
 1 : 1
 2 : 1
 3 : 1
 4 : 1
 5 : 1
 9 : 3
10 : 1
11 : 3
12 : 1

Second question: I need to count how many times each number of every row in "Values" column occured in this row.
For example:

 0 : 2
 1 : 3
 2 : 1
 3 : 1
 4 : 1
 5 : 2

 9 : 3
10 : 2
11 : 3
12 : 1

 5 : 1
 1 : 2
10 : 1
 0 : 1

How can I do that?

1
  • What are your Values? Are they strings like '0,1,2,3,4,5' or lists of numbers like [0,1,2,3,4,5]? Commented Oct 24, 2016 at 21:43

1 Answer 1

2

Assuming your Values column contains strings:

In [163]: df
Out[163]:
                 Values   Bought
0           0,1,2,3,4,5        0
1  9,10,11,9,11,12,9,11  9,12,11
2        5, 1, 1, 10, 0        0

In [164]: df.dtypes
Out[164]:
Values    object
Bought    object
dtype: object

In [165]: df.Values.str.split(',\s*', expand=True).stack().value_counts()
Out[165]:
11    3
1     3
9     3
5     2
0     2
10    2
12    1
4     1
3     1
2     1
dtype: int64

In [166]: df.Values.str.split(',\s*', expand=True).apply(lambda x: x.value_counts(), axis=1).fillna(0).astype(int)
Out[166]:
   0  1  10  11  12  2  3  4  5  9
0  1  1   0   0   0  1  1  1  1  0
1  0  0   1   3   1  0  0  0  0  3
2  1  2   1   0   0  0  0  0  1  0

Assuming your Values column contains lists of numbers:

In [193]: df
Out[193]:
                          Values
0             [0, 1, 2, 3, 4, 5]
1  [9, 10, 11, 9, 11, 12, 9, 11]
2               [5, 1, 1, 10, 0]

In [194]: df.Values.apply(pd.Series).stack().value_counts().sort_index()
Out[194]:
0.0     2
1.0     3
2.0     1
3.0     1
4.0     1
5.0     2
9.0     3
10.0    2
11.0    3
12.0    1
dtype: int64

In [195]: df.Values.apply(pd.Series).apply(lambda x: x.value_counts(), axis=1).fillna(0).astype(int)
Out[195]:
   0.0   1.0   2.0   3.0   4.0   5.0   9.0   10.0  11.0  12.0
0     1     1     1     1     1     1     0     0     0     0
1     0     0     0     0     0     0     3     1     3     1
2     1     2     0     0     0     1     0     1     0     0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.