简体   繁体   English

如何将列表列表作为列添加到现有数据框

[英]How to add list of lists as a column to existing data frame

I have created a dataframe "df" which looks like this: 我创建了一个数据框“ df”,如下所示:

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

now I have three lists 现在我有三个清单

1. from=['12','18',['11','10'],['12','4','8']]
2. to = [['11','9'],'','8','3']
3. status = ['yes','no',['yes','no'],'']

I want to add these 3 lists to my existing dataframe df and it should look like this 我想将这3个列表添加到我现有的数据框df中,它应该看起来像这样

  Name          From   To   Status
0. School        12    11   Yes
0. School               9
1. Organisation  18         No
2. Teacher       11     8   Yes
2. Teacher       10         No
3. Guest         12     3
3. Guest          4
3. Guest          8

I have tried df['from']=from and df['to']=to But this didn't give me table as I expected. 我已经尝试过df['from']=fromdf['to']=to但是这并没有像我期望的那样给我表。

first,we should flatten the list with a index,then use the concat method of pandas like this: 首先,我们应该使用索引将列表弄平,然后使用pandasconcat方法,如下所示:

import pandas as pd
df = pd.DataFrame({"Name":["School","Organisation","Teacher","Guest"]})
From = ['12','18',['11','10'],['12','4','8']]
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="From"
list_flat,list_index=flat(eval(x))
dataframe = pd.DataFrame({x:list_flat},index=list_index)
df = pd.concat([df['Name'],dataframe],axis=1,sort=False)

the result is: 结果是:

           Name From
0        School   12
1  Organisation   18
2       Teacher   11
2       Teacher   10
3         Guest   12
3         Guest    4
3         Guest    8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM