Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Creating Pandas Dataframe can be achieved in multiple ways. Let’s see how can we create a Pandas DataFrame from Lists.
Create a Pandas DataFrame from Lists
Python3
# import pandas as pd import pandas as pd # list of strings lst = [ 'Geeks' , 'For' , 'Geeks' , 'is' , 'portal' , 'for' , 'Geeks' ] # Calling DataFrame constructor on list df = pd.DataFrame(lst) df |
Output:
Dataframe using list with index and column names
Python3
# import pandas as pd import pandas as pd # list of strings lst = [ 'Geeks' , 'For' , 'Geeks' , 'is' , 'portal' , 'for' , 'Geeks' ] # Calling DataFrame constructor on list # with indices and columns specified df = pd.DataFrame(lst, index = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ], columns = [ 'Names' ]) df |
Output:
Create a Pandas DataFrame from Lists Using zip() for zipping two lists
Python3
# import pandas as pd import pandas as pd # list of strings lst = [ 'Geeks' , 'For' , 'Geeks' , 'is' , 'portal' , 'for' , 'Geeks' ] # list of int lst2 = [ 11 , 22 , 33 , 44 , 55 , 66 , 77 ] # Calling DataFrame constructor after zipping # both lists, with columns specified df = pd.DataFrame( list ( zip (lst, lst2)), columns = [ 'Name' , 'val' ]) df |
Output:
Creating DataFrame using multi-dimensional list
Python3
# import pandas as pd import pandas as pd # List1 lst = [[ 'tom' , 25 ], [ 'krish' , 30 ], [ 'nick' , 26 ], [ 'juli' , 22 ]] df = pd.DataFrame(lst, columns = [ 'Name' , 'Age' ]) df |
Output:
Using multi-dimensional list with column name and dtype specified.
Python3
# import pandas as pd import pandas as pd # List1 lst = [[ 'tom' , 'reacher' , 25 ], [ 'krish' , 'pete' , 30 ], [ 'nick' , 'wilson' , 26 ], [ 'juli' , 'williams' , 22 ]] df = pd.DataFrame(lst, columns = [ 'FName' , 'LName' , 'Age' ], dtype = float ) df |
Output:
Using lists in dictionary to create dataframe
Python3
# importing pandas as pd import pandas as pd # list of name, degree, score nme = ["aparna", "pankaj", "sudhir", "Geeku"] deg = ["MBA", "BCA", "M.Tech", "MBA"] scr = [ 90 , 40 , 80 , 98 ] # dictionary of lists dict = { 'name' : nme, 'degree' : deg, 'score' : scr} df = pd.DataFrame( dict ) df |
Output: