Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Data Science by (50.2k points)

I have a Python DataFrame with multiple columns.

2u    2s    4r     4n     4m   7h   7v

0     1     1      0      0     0    1

0     1     0      1      0     0    1

1     0     0      1      0     1    0

1     0     0      0      1     1    0

1     0     1      0      0     1    0

0     1     1      0      0     0    1

What I want to do is to convert this pandas.DataFrame into a list like following

X = [

     [0, 0, 1, 1, 1, 0],

     [1, 1, 0, 0, 0, 1],

     [1, 0, 0, 0, 1, 1],

     [0, 1, 1, 0, 0, 0],

     [0, 0, 0, 1, 0, 0],

     [0, 0, 1, 1, 1, 0],

     [1, 1, 0, 0, 0, 1]

    ]

2u 2s 4r 4n 4m 7h 7v are column headings. It will change in different situations, so don't bother about it.

1 Answer

0 votes
by (108k points)

It just looks like a transposed matrix:

df.values.T.tolist()

[list(l) for l in zip(*df.values)]

[[0, 0, 1, 1, 1, 0],

 [1, 1, 0, 0, 0, 1],

 [1, 0, 0, 0, 1, 1],

 [0, 1, 1, 0, 0, 0],

 [0, 0, 0, 1, 0, 0],

 [0, 0, 1, 1, 1, 0],

 [1, 1, 0, 0, 0, 1]]

This returns a list of a list.

This code above could be apparently modified to list(df.values.T.flatten()) so the values will be kept by column.

If you wish to Learn more about Pandas visit this Pandas Tutorial.

Browse Categories

...