1

I want to convert a data frame so that each column becomes one list, named by the column name. To give an example, suppose I have the following data frame

import pandas as pd

d = {'A' : [1, 2, 3, 4],
     'B' : ['x', 'y', 'z', 'w']}

df = pd.DataFrame(d)

print(df)

   A  B
0  1  x
1  2  y
2  3  z
3  4  w

The desired output is to have

A = [1,2,3,4]
B = ['x', 'y', 'z', 'w']

I know how to get the column names as well as the values into list format separately or together in the following ways:

test1 = df.T.reset_index().values.tolist()
print(test1)
[['A', 1, 2, 3, 4], ['B', 'x', 'y', 'z', 'w']]

test2 = df.T.values.tolist()        
print(test2)
[[1, 2, 3, 4], ['x', 'y', 'z', 'w']]

test3 = df.columns.values.tolist()
print(test3)
['A', 'B']                 

But I cannot figure out if/how I can name the lists created in test2 the names as given by the column names.

elol
  • 33
  • 5
  • 1
    `A, B = df.T.values.tolist()`? – cs95 Dec 13 '17 at 10:24
  • Oh, I see. You want to create a variable number of variables. – cs95 Dec 13 '17 at 10:25
  • Iterate over `df.columns` and `df.T.values.tolist()` and assign to a dictionary. – cs95 Dec 13 '17 at 10:25
  • 2
    In my opinion the best `d = df.to_dict('l')` – jezrael Dec 13 '17 at 10:26
  • 1
    Simply create dictionary of columns as keys and values as `list`s. Then for select need `print (d['A'])` – jezrael Dec 13 '17 at 10:30
  • @cᴏʟᴅsᴘᴇᴇᴅ It is not obvious to me that it is a duplicate question, but I could have been clearer that I want to achieve the suggested solution without having to write out the list names (getting the names of the lists automatically is necessary due to large number of columns). Also - I accept your call regarding the duplicate nature of my question. I will go through the other question in detail to see what I can learn, I hadn't seen it before. – elol Dec 13 '17 at 10:37
  • 1
    @jezrael That was not really an answer to the question I asked, but you provided an even better solution than the one I had in mind. Thank you. – elol Dec 13 '17 at 10:38
  • @elol - It is for discussion it it is dupe or not, in my opinion not. But cᴏʟᴅsᴘᴇᴇᴅ have different opinion, so I respect it and no reopen question. – jezrael Dec 13 '17 at 11:09

0 Answers0