Home > Blockchain >  How to create list that return the occurences of Id_1 in a dataframe?
How to create list that return the occurences of Id_1 in a dataframe?

Time:12-06

I want to create list that return the occurences of Id_1 in a dataframe:

Id_1  Id_2
0   1401    1
1   1401    3
2   1801    0     
3   1801    2
4   1801    0
5   1801    0
6   2001    1
7   2001    5
8   2201    0
9   2201    0

# I would like this output:
L = [(1401,2), (1801, 4),(2001,2), (2201,2)]

CodePudding user response:

Use value_counts and to_dict:

L = df.value_counts('Id_1').to_dict().items()
print(list(L))

# Output:
[(1801, 4), (1401, 2), (2001, 2), (2201, 2)]

CodePudding user response:

Use value_counts() to compute the frequency of the occurrences and turn them into a dictionary with .to_dict(). You can then use list comprehension to have the list of tuples.

counts = df['Id_1'].value_counts().to_dict()
L = [(k, v) for k, v in counts.items()]
  • Related