Gworld
Gworld

Reputation: 103

How to split a list based on another list of values?

I have a list like this:

some = [["a", "1", "c"], ["a", "2", "@"], ["b", "1", "9"], ["c", "1", "pw"], ["c", "2", "af"]]

The list is ordered based on second column. So all rows are sorted here. I am trying the split the list into the n different lists based on unique values. I tried the following

import pandas as pd
uniquevals = pd.DataFrame(some)[0].value_counts()
newlist = []
for i in uniquevals:
    newlist = some[1:i]
    print(newlist)
    print("Done\n")

and the result is

[['a', '2', '@']]
Done

[['a', '2', '@']]
Done

[]
Done

But ideally, I want rows in the column to split based on the count of unique values of first column. Here a has two values and b has one value and c has two values. Ideal output should be:

[["a", "1", "c"], ["a", "2", "@"]]
Done

[["b", "1", "9"]]
Done

[["c", "1", "pw"], ["c", "2", "af"]]
Done

Upvotes: 1

Views: 239

Answers (1)

U13-Forward
U13-Forward

Reputation: 71620

Why not just use pd.DataFrame.groupby:

some = [["a", "1", "c"], ["a", "2", "@"], ["b", "1", "9"], ["c", "1", "pw"], ["c", "2", "af"]]
uniquevals = pd.DataFrame(some)
for _, i in uniquevals.groupby(0):
    print(i.to_numpy().tolist())
    print("Done\n")

Output:

[['a', '1', 'c'], ['a', '2', '@']]
Done

[['b', '1', '9']]
Done

[['c', '1', 'pw'], ['c', '2', 'af']]
Done

Upvotes: 1

Related Questions