Mohi
Mohi

Reputation: 123

Convert DataFrame into multi-dimensional array with the column names of DataFrame

Below is the DataFrame I want to action upon:

df = pd.DataFrame({'A': [1,1,1],
                   'B': [2,2,3],
                   'C': [4,5,4]})

Each row of df creates a unique key. Objective is to create the following list of multi-dimensional arrays:

parameter = [[['A', 1],['B', 2], ['C', 4]],
             [['A', 1],['B', 2], ['C', 5]],
             [['A', 1],['B', 3], ['C', 4]]]

Problem is related to this question where I have to iterate over the parameter but instead of manually providing them to my function, I have to put all parameter from df (rows) in a list.

Upvotes: 1

Views: 457

Answers (1)

yatu
yatu

Reputation: 88236

You could use the following list comprehension, which zips the values on each row with the columns of the dataframe:

from itertools import repeat

[list(map(list,zip(cols, i))) for cols, i in zip(df.values.tolist(), repeat(df.columns))]

[[[1, 'A'], [2, 'B'], [4, 'C']],
 [[1, 'A'], [2, 'B'], [5, 'C']],
 [[1, 'A'], [3, 'B'], [4, 'C']]]

Upvotes: 1

Related Questions