简体   繁体   中英

Create two columns from two different sized columns

I am trying to create two columns from two lists.

I tried using zip to build the DataFrame and insert the lists, but the larger list was cut off.

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']) 

My output:

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

Good output:

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

One way is using 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

You can use pd.DataFrame.from_records and transpose:

df = pd.DataFrame.from_records([list1, list2]).T.fillna('')
# df.columns = ['list1', 'list2']

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

You can build a horizontal df and then transpose.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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