简体   繁体   中英

Python/Pandas: How to import three entire str lists using pandas library to create three columns resulting in an .xlsx file (excel file)?

I have already installed pandas and imported/referred it into my code.

import pandas as pd

Currently, I have three string lists each containing 10+ lines of elements each.

list1 = ['string1', 'string2', 'string3', 'string4']
list2 = ['string1', 'string2', 'string3', 'string4'] 
list3 = ['string1', 'string2', 'string3', 'string4']

I'd like to refer to these lists, import them into their own DataTable separated by columns (each list would be in their own column). It would read each line and place it in their respective row.

Goal: Refer to three lists, place each in their own column, and create an excel file. Any help would be appreciated (resource, example code, whatever!)

CN = Column Name

0  CN1   CN2   CN3
1 list1 list2 list3
2
3
4
4

Once lists are referred to, DataTable would look like this:

0 CN1     CN2     CN3
1 string1 string1 string1
2 string2 string2 string2
3 string3 string3 string3
4 string4 string4 string4

if I understand correctly, here is one way by preparing a dictionary:

dictdata = {}
dictdata["CN1"] = list1
dictdata["CN2"] = list2
dictdata["CN3"] = list3

df = pd.DataFrame(dictdata)
df.to_excel('/home/data.xlsx', engine = 'xlsxwriter')

or you can use zip :

dictdata = dict(zip(["CN1","CN2","CN3"],zip(list1,list2,list3)))
df = pd.DataFrame(dictdata)
df.to_excel('/home/data.xlsx', engine = 'xlsxwriter')

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