Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add nested list as new column to existing pandas data-frame

I have created a dataframe "df" which looks like this:

   Name
0. School
1. Organisation 
2. Teacher 
3. Guest

now I have three lists

1. A = ['','','',['12','4']]
2. B = ['','','',['3','8']]
3. status = ['','','','[['yes','no','yes'],['no','yes','no']]]
4. letter = ['', '', '', [[['K', 'L'], ['L'], ['L']], [['O'], ['P', 'O'], ['K']]]]

I want to add these 4 lists to my existing dataframe df and it should look like this

  Name            A1    A2   status  letter
0. School                 
1. Organisation          
2. Teacher       
3. Guest          12     3   yes     K
3. Guest          12     3   yes     L
3. Guest          12     3   no      L
3. Guest          12     3   yes     L
3. Guest           4     8   no      O
3. Guest           4     8   yes     P
3. Guest           4     8   yes     O
3. Guest           4     8   no      K

I have tried df['from']=from and df['to']=to But this didn't give me table as I expected.

I have tried this as well:

dfa=pd.DataFrame({"Names":names})

def flat(nums):
    res = []
    index = []
    for i in range(len(nums)):
        if isinstance(nums[i], list):
            res.extend(nums[i])
            index.extend([i]*len(nums[i]))
        else:
            res.append(nums[i])
            index.append(i)
    return res,index

    x="A1"
    list_flat,list_index=flat(eval(x))
    dataframe = pd.DataFrame({x:list_flat},index=list_index)
    df = pd.concat([df['Names'],dataframe],axis=1,sort=False)

    x="A2"
    list_flat,list_index=flat(eval(x))
    dataframe = pd.DataFrame({x:list_flat},index=list_index)
    df= pd.concat([df,dataframe],axis=1,sort=False)

    x="status"
    list_flat,list_index=flat(eval(x))
    dataframe = pd.DataFrame({x:list_flat},index=list_index)
    df = pd.concat([df,dataframe],axis=1,sort=False)

    x="letter"
    list_flat,list_index=flat(eval(x))
    dataframe = pd.DataFrame({x:list_flat},index=list_index)
    df = pd.concat([df,dataframe],axis=1,sort=False)

But instead of appearing on different rows nested lists are appearing on same row like this

Name              A1    A2    status                 letter
0. School                 
1. Organisation          
2. Teacher       
3. Guest          12     3   ['yes','no','yes']     [['K','L'],['L'],['L']]
3. Guest           4     8   ['no','yes','no']      [['O'],['P','O'],['K']]
like image 822
Miffy Avatar asked Jan 20 '26 13:01

Miffy


1 Answers

Can you try the following:

name = ['School', 'Organization', 'Teacher', 'Guest']
A = ['','','',['12','4']]
B = ['','','',['3','8']]
status = ['','','',[['yes','no','yes'],['no','yes','no']]]
letter = [['', '', '', [[['K', 'L'], ['L'], ['L']], [['O'], ['P', 'O'], ['K']]]]]

final_list = []
for a, b, c, d, e in zip(name, A, B, status, letter[0]):
    if any([b, c, d, e]):
        for b1, c1, d1, e1 in zip(b, c, d, e):
            for d2, e2 in zip(d1, e1):
                for e3 in e2:
                    final_list.append([a, b1, c1, d2, e3])
    else:
        final_list.append([a, b, c, d, e])

df = pd.DataFrame(final_list, columns=['Name', 'A1', 'A2', 'status', 'letter'])

Output:

            Name  A1 A2 status letter
0         School                     
1   Organization                     
2        Teacher                     
3          Guest  12  3    yes      K
4          Guest  12  3    yes      L
5          Guest  12  3     no      L
6          Guest  12  3    yes      L
7          Guest   4  8     no      O
8          Guest   4  8    yes      P
9          Guest   4  8    yes      O
10         Guest   4  8     no      K
like image 133
Jeril Avatar answered Jan 23 '26 02:01

Jeril



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!