Home > other >  How can I create a list of the number of times the same number appears in column B?
How can I create a list of the number of times the same number appears in column B?

Time:07-29

Let say I have a dataframe :

A     B
1     1401
2     1401
3     1401
4     1601
5     2201
6     2201
7     6401
8     6401
9     6401
10    6401

I would like to obtain this ouput:

L1 = [1401, 1601, 2201, 6401]
L2 = [3, 1, 2, 4] (the number of times the same number appears in column B)

Thanks !

CodePudding user response:

Answer :

df.B.value_counts().values

CodePudding user response:

You can use:

L1, L2 = zip(*df['B'].value_counts(sort=False).iteritems())
# note that this generates tuples, not lists

Or in several lines:

s = df['B'].value_counts(sort=False)
L1 = list(s.index)
L2 = list(s)

output:

L1
# [1401, 1601, 2201, 6401]

L2
# [3, 1, 2, 4]
  • Related