Split a Given List and Insert in Excel File in Python

In this article, let us see how to split a given list and insert it into an excel file using Python.

In Python, how do you split a list?

We can split the given list of elements using slicing.

Pandas Module in Python:

Pandas is an open-source library designed to make it simple and natural to work with relational or labeled data. It includes a number of data structures and methods for working with numerical data and time series. This library is based on the NumPy Python library. Pandas is quick and has a high level of performance and productivity for its users.

Pandas is widely used for data science, data analysis, and machine learning activities. It is built on top of Numpy, a library that supports multi-dimensional arrays. Pandas, as one of the most popular data-wrangling programs, is normally included in every Python distribution, from those that come with your operating system to commercial vendor versions like ActiveState’s ActivePython.

Splitting a Given List and Insert in Excel File in Python

Using pandas, we can easily edit the columns and use the dataframe.to excel() function to quickly insert the filtered elements into an excel file.

The list is converted into data, rows, and columns by using a data frame. We can use the splitter list in an Excel sheet this way.

Approach:

  • Import pandas module using the import keyword
  • Give the list as static input and store it in a variable.
  • Create a dataframe object using the DataFrame() function of the pandas module
  • Creating 4 columns on the dataframe(Employ_id, Employee_Name, Designation, Salary) by applying slicing on the given list
  • Save all the above 4 columns of the dataframe into an Excel file using the to_excel() function
  • Here, the to_excel() fucntion is used to insert an object into an Excel file.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword 
import pandas  
# Give the list as static input and store it in a variable.
gvn_lst = [1, 'John','Software developer', 80000,
         2,'Virat', 'Project associate', 50000,
         3, 'Nick','Testing Engineer', 40000,
         4, 'Rosy','Networking department', 35000] 

# Create a dataframe object using the DataFrame() function of the pandas module
datafrme = pandas.DataFrame() 
# Creating 4 columns on the dataframe(Employ_id, Employee_Name, Designation, Salary) 
# by applying slicing on the given list
datafrme['Employ_id'] = gvn_lst[0::4] 
datafrme['Employee_Name'] = gvn_lst[1::4] 
datafrme['Designation'] = gvn_lst[2::4]
datafrme['Salary'] = gvn_lst[3::4]

# Save all the above 4 columns of the dataframe into an Excel file using the to_excel()
# function
# Here, the to_excel() function is used to insert an object into an Excel file.
datafrme.to_excel('OutputExcelFile.xlsx', index = False)

Output:

Output Excel File after Splitting the Given List