In this tutorial, We will see different ways of Creating a pandas Dataframe from List.
You can use Dataframe()
method of pandas
library to convert list to DataFrame. so first we have to import pandas library into the python file using import statement.
So let’s see the various examples on creating a Dataframe with the list :
Example 1 : create a Dataframe by using list .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Example 1 : # import pandas package as pd in this code import pandas as pd # give list of strings stringList = ["java","2","blog","dot","com"] # Convert the given list into pandas DataFrame df = pd.DataFrame(stringList) print(df) |
Output :
1 2 3 4 5 6 7 8 |
0 0 java 1 2 2 blog 3 dot 4 com |
Example 2: Create a Dataframe by using list with index and column names.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# import pandas as pd import pandas as pd # give list of strings stringList = ["java","2","blog","dot","com"] # Convert the given list into pandas DataFrame # with indices and column name specified df = pd.DataFrame(stringList, index =['a', 'b', 'c', 'd','e'], columns =['names']) print(df) |
Output :
1 2 3 4 5 6 7 8 |
names a java b 2 c blog d dot e com |
Example 3 : create a Dataframe by list with using zip() function and column names.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# import pandas package as pd in this code import pandas as pd # give list of strings stringList = ["java","2","blog","dot","com"] # give list of strings stringLenList = [4, 1, 4, 3, 3] # Convert the given two lists into DataFrame # after zipping both lists, with columns specified. df = pd.DataFrame(list(zip(stringList, stringLenList)), columns =['names', 'length']) print(df) |
Output :
1 2 3 4 5 6 7 8 |
names length 0 java 4 1 2 1 2 blog 4 3 dot 3 4 com 3 |
Example 4: Create a Dataframe by using list of lists and column names.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# import pandas package as pd in this code import pandas as pd # given list of lists. lst = [['ankit', 22], ['rahul', 25], ['priya', 27], ['golu', 22]] # Convert the given list of lists into pandas DataFrame df = pd.DataFrame(lst, columns =['Name', 'Age']) print(df) |
Output :
1 2 3 4 5 6 7 |
Name Age 0 ankit 22 1 rahul 25 2 priya 27 3 golu 22 |
Example 5: Create a Dataframe by using list as a value in dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# import pandas package as pd in this code import pandas as pd # list of name, degree, score name = ["ankit", "aishwarya", "priya", "Golu"] degree = ["btech", "btech", "mba", "bhms"] score = [90, 40, 80, 98] # dictionary of lists dict = {'name': name, 'degree': degree, 'score': score} # Convert the given dictionary into pandas DataFrame df = pd.DataFrame(dict) print(df) |
Output :
1 2 3 4 5 6 7 |
degree name score 0 btech ankit 90 1 btech aishwarya 40 2 mba priya 80 3 bhms Golu 98 |
That’s all about how to Create a Pandas Dataframe from List.