Home > database >  How to generate a list from a pandas dataframe with column name and values as nested list
How to generate a list from a pandas dataframe with column name and values as nested list

Time:11-05

How to generate a list from a pandas dataframe with column name and values as nested list? this is my dataframe:

  a b c  d
0 1 5 9  13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16

i would like to generate a list

list1 = [[a,1], [a,2], [a,3],[a,4]]
list2 = [[b,5], [b,6], [b,7],[b,8]]

CodePudding user response:

One can use a list comprehension for that.

  • For list1

    list1 = [[a, b] for a, b in zip(['a'] * len(df), df['a'])]
    
    [Out]: [['a', 1], ['a', 2], ['a', 3], ['a', 4]]
    
  • For list2:

    list2 = [[a, b] for a, b in zip(['b'] * len(df), df['b'])]
    
    [Out]: [['b', 5], ['b', 6], ['b', 7], ['b', 8]]
    

CodePudding user response:

You could do the following:

import pandas as pd

df = pd.DataFrame(
    {'a': {0: 1, 1: 2, 2: 3, 3: 4},
     'b': {0: 5, 1: 6, 2: 7, 3: 8},
     'c': {0: 9, 1: 10, 2: 11, 3: 12},
     'd': {0: 13, 1: 14, 2: 15, 3: 16}})

lists = [[[c,x] for x in col] for c,col in df.iteritems()]

print(lists[0]) # [['a', 1], ['a', 2], ['a', 3], ['a', 4]]
print(lists[1]) # [['b', 5], ['b', 6], ['b', 7], ['b', 8]]

lists is a list containing the results corresponding to each column.

CodePudding user response:

lst = []
df.apply(lambda x:lst.append([[x.name,i] for i in x]))
print(*lst, sep='\n')
[['a', 1], ['a', 2], ['a', 3], ['a', 4]]
[['b', 5], ['b', 6], ['b', 7], ['b', 8]]
[['c', 9], ['c', 10], ['c', 11], ['c', 12]]
[['d', 13], ['d', 14], ['d', 15], ['d', 16]]
  • Related