Hướng dẫn append multiple lists python

There can be an application requirement to append elements of 2-3 lists to one list. This kind of application has the potential to come into the domain of Machine Learning or sometimes in web development as well. Let’s discuss certain ways in which this particular task can be performed.

Show

Method #1 : Using + operator 
This can be easily done using the plus operator as it does the element addition at the back of the list. Similar logic is extended in the case of multiple lists.

Python3

test_list1 = [1, 3, 5, 5, 4]

test_list2 = [4, 6, 2, 8, 10]

test_list3 = [7, 5, 2, 9, 11]

print ("The original list 1 is : " + str(test_list1))

print ("The original list 2 is : " + str(test_list2))

print ("The original list 3 is : " + str(test_list3))

test_list1 = test_list1 + test_list2 + test_list3

print ("The extended and modified list is : " +  str(test_list1))

Output:

The original list 1 is : [1, 3, 5, 5, 4]
The original list 2 is : [4, 6, 2, 8, 10]
The original list 3 is : [7, 5, 2, 9, 11]
The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]

  
Method #2 : Using itertools.chain() 
The chain function can also be employed to perform this particular tasks as it uses the iterator to perform this and hence offers better performance over the above method.

Python3

from itertools import chain

test_list1 = [1, 3, 5, 5, 4]

test_list2 = [4, 6, 2, 8, 10]

test_list3 = [7, 5, 2, 9, 11]

print ("The original list 1 is : " + str(test_list1))

print ("The original list 2 is : " + str(test_list2))

print ("The original list 3 is : " + str(test_list3))

test_list1 = list(chain(test_list1, test_list2, test_list3))

print ("The extended and modified list is : " +  str(test_list1))

Output:

The original list 1 is : [1, 3, 5, 5, 4]
The original list 2 is : [4, 6, 2, 8, 10]
The original list 3 is : [7, 5, 2, 9, 11]
The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]

You have some list or list of lists and you want to convert them into a Pandas DataFrame. For example, you have some data about fruit prices in a python lists and you want to create a DataFrame like this one.

Solution –

Pandas DataFrame from a Single List –

Let’s first create a pandas DataFrame from a single list using the fruits names.

To create a DataFrame first we have to import the pandas library

# import pandas library import pandas as pd

Then create the list.

# fruit list fruits = ['Apple','Avocado','Banana','Coconut','Jackfruit','Orange']

Now, to turn this list into a pandas DataFrame, all we have to do is pass this list to pandas DataFrame constructor pd.DataFrame.

# create dataframe from list df = pd.DataFrame(fruits) print(df)

Now, you can see that index is looking good but we do not have a descriptive column name. To change the column name or the index, we can pass the labels to the pd.DataFrame columns and index argument.

# create dataframe from list df = pd.DataFrame(data=fruits, index= [1, 2, 3, 4, 5, 6], columns=['fruit']) df

Pandas DataFrame from Multiple Lists –

Now, let’s create a pandas dataframe from multiple lists using the zip function. To create a dataframe from multiple lists we have to first zip those list and convert them into a list. Then we pass them to the pandas dataframe.

# lists fruits = ['Apple','Avocado','Banana','Coconut','Jackfruit','Orange'] prices = [200, 200, 40, 30, 500, 70] # create dataframe using zip and list df = pd.DataFrame(list(zip(fruits, prices)), columns=['fruit', 'price']) df

Pandas DataFrame from List of Lists –

Now, let’s create the complete dataframe using list of lists. First create the list of lists and then pass it to the pd.DataFrame.

# list of lists fruits_data = [['Apple', '1 kg', 200], ['Avocado', '1 kg', 200], ['Banana', '1 kg', 40], ['Coconut', '1 piece', 30], ['Jackfruit', '1 piece', 500], ['Orange', '1 kg', 70]] # create df from list of lists df = pd.DataFrame(fruits_data, columns=['fruit','quantity','price']) df

That’s it. We learned how to create a dataframe from a list, from more than two lists and from lists of lists.

Related Posts –

If you want to learn more about pandas, please subscribe to our blog below.

You might need to convert your numpy arrays into a DataFrame. Or maybe you have a list of values (while working in vanilla python) and you want to turn them into a DataFrame within Pandas. That is where list to dataframe comes into play.

pandas.DataFrame(Your_list_or_lists)

I do this most often when I’m iterating through a for loop, saving the values, and then need to create a new DataFrame from them. Important: When passing multiple lists, you must pass lists that represent rows.

Pseudo Code: With your python lists, turn them into a pandas DataFrame

Since creating a DataFrame from a list uses the standard pd.DataFrame(), you only have to worry about those parameters

  • data = The data that you want your DataFrame to be created from. In this case, it is going to be the list(s) you pass. Each list represents a row in your future DataFrame.
  • index = You can pass an index that is the same length as the number of lists you pass. Think of index as row labels
  • columns = Your column names. The length of this list of columns must match the number of items in your child lists.

Now the fun part, let’s take a look at a code sample

You may want to create a DataFrame from a list or list of lists. In this case, all you need to do is call the general pd.DataFrame() function and pass your data.

We will run through 3 examples:

  1. Creating a DataFrame from a single list
  2. Creating a DataFrame from multiple lists
  3. Creating a DataFrame from multiple lists and specifying column names
  4. Creating a DataFrame from multiple lists and specifying column names and index

But first, let's create some lists

list1 = ["Foreign Cinema", 50] list2 = ["Liho Liho", 45] list3 = ["500 Club", 102] list4 = ["The Square", 65]

To start off, let's create a DataFrame from a single list. Do do this I'm going to call pd.DataFrame, then pass data=my_list.

You can see, when I pass one list, pandas returns a single column DataFrame. The list values are the row within a single column.

If I wanted to create a DataFrame with multiple rows (I do this most of the time), then you just need to pass a list of lists in to data

pd.DataFrame(data=[list1, list2, list3, list4])

Next, let's specify column names. Pass your column names to the column parameter. Make sure that the number of columns you specify equals the number of columns in your DataFrame.

pd.DataFrame(data=[list1, list2, list3, list4], columns=['Name', 'num_customers'])

Finally, let's create a DataFrame with a specific index. To do this I'll pass a list of index labels to the index parameter.

pd.DataFrame(data=[list1, list2, list3, list4], columns=['Name', 'num_customers'], index=['res1', 'res2', 'res3', 'res4'])

Check out more Pandas functions on our Pandas Page