从两个大小不同的列中创建两个列

时间:2019-09-03 10:12:05

标签: python pandas

我正在尝试从两个列表中创建两列。

我尝试使用zip来构建DataFrame并插入列表,但是较大的列表被剪掉了。

import pandas as pd

list1 = ['new book revealing', 'library for topic modelling']
list2 = ['potentially embarrassing', 'several international', 'daily newspaper'] 
df = pd.DataFrame(list(zip(list1, list2)), columns =['list1', 'list2']) 

我的输出:

                 list1            list2
0   new book revealing            potentially embarrassing
1   library for topic modelling   several international

好的输出:

                 list1            list2
0   new book revealing            potentially embarrassing
1   library for topic modelling   several international 
2                                 daily newspaper

3 个答案:

答案 0 :(得分:2)

一种方法是使用zip_longest

import itertools
pd.DataFrame(itertools.zip_longest(list1, list2), columns =['list1', 'list2']) 

                        list1                     list2
0           new book revealing  potentially embarrassing
1  library for topic modelling     several international
2                         None           daily newspaper

答案 1 :(得分:2)

您可以使用pd.DataFrame.from_records并转置:

rm -rf ~/.local/lib/python2.7/site-packages/requests/packages/urllib3/

答案 2 :(得分:1)

您可以构建水平df,然后转置。

pd.DataFrame([list1, list2], index=['list1', 'list2']).T.fillna('')

    list1                       list2
0   new book revealing          potentially embarrassing
1   library for topic modelling several international
2                               daily newspaper