map a data frame to a nested list

Question:

I have a data frame with 2 columns
and I also have a nested list containing the elements of the first column

I want to append the remaining column elements and the index to the nested list

|Column A  | Column B |
| -------- | -------- |
|100,2     | A        |
|101,5     | B        |
|103,6     | C        |
|104,6     | D        |
|105,7     | E        |

the nested list looks like

[[100.2,101.5],[103.6,104.6],[105.7]]

The output

[[[0,100.2,'A'],[1,101.5,'B']],[[3,103.6,'C'],[4,104.6,'D']],[[5,105.7,'E']]] 

from a dataframe to a nested list

Asked By: ZAHR

||

Answers:

Use pandas to solve above problem with simplicity.

    import pandas as pd
    df = pd.DataFrame({'Column A': [100.2,101.5,103.6,103.6,105.7],
                       'Column B': ['A', 'B', 'C', 'D', 'E']})
    grouped = df.groupby('Column A')
    
    result = [[[i, row['Column A'], row['Column B']] for i, row in 
group.iterrows()] for _, group in grouped]
print(result)

Result:

[[[0, 100.2, 'A']], [[1, 101.5, 'B']], [[2, 103.6, 'C'], [3, 103.6, 'D']], [[4, 105.7, 'E']]]

Process finished with exit code 0
Answered By: Raushan Kumar

We can use pandas reset_index() and tolist() functions to solve above

import pandas as pd
df = pd.DataFrame({'Column A': [100.2,101.5,103.6,103.6,105.7],
                       'Column B': ['A', 'B', 'C', 'D', 'E']})
df = df.reset_index(level=0)

print(df.values.tolist())

output:

[[0, 100.2, 'A'],
 [1, 101.5, 'B'],
 [2, 103.6, 'C'],
 [3, 103.6, 'D'],
 [4, 105.7, 'E']]
Answered By: ForamJ
import pandas as pd
df = pd.DataFrame({'A': [100.2,101.5,103.6,104.6,105.7],
                   'B': ['A', 'B', 'C', 'D', 'E']})
a = [[100.2,101.5],[103.6,104.6],[105.7]]

df1 = df.reset_index().set_index('A', drop=False)
[[df1.loc[v].tolist() for v in row] for row in a]

produces

[[[0, 100.2, 'A'], [1, 101.5, 'B']],
 [[2, 103.6, 'C'], [3, 104.6, 'D']],
 [[4, 105.7, 'E']]]
Answered By: Antony Hatchkins
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.