[英]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. 我尝试使用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'])
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
: 一种方法是使用
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: 您可以使用
pd.DataFrame.from_records
并转置:
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. 您可以构建水平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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.