In Pandas, Dataframe can be created in multiple ways. In this article, we will learn how to create a DataFrame using List.
Let’s try to understand the creation of dataframe using list with help of multiple examples.
Example #1:
# Python example to create a dataframe using list # importing pandas as pd import pandas as pd # list of strings lst = ['Python', 'Pandas', 'is', 'best', 'Python', 'blog'] # Calling DataFrame constructor on lst df = pd.DataFrame(lst) # printing dataframe print(df )
Output:
0 0 Python 1 Pandas 2 is 3 best 4 Python 5 blog
Example #2: Specify column name
# import pandas as pd import pandas as pd # list of strings lst = [['John', 'Wick', 22], ['Romi', 'Wilson', 23], ['Python', 'Pandas', 25]] # Calling DataFrame constructor on list of lists # with columns names df = pd.DataFrame(lst, columns =['F_Names', 'L_Name', 'Age']) print(df )
Output:
F_Names L_Name Age 0 John Wick 22 1 Romi Wilson 23 2 Python Pandas 25
Example #3: Specify Index and Column name
# import pandas as pd import pandas as pd # list of strings lst = ['Python', 'Pandas', 'is', 'best', 'Python', 'blog'] # Calling DataFrame constructor on list # with indices and columns specified df = pd.DataFrame(lst, index = ['a', 'b', 'c'], columns =['F_Names', 'L_Name', 'Age']) print(df )
Output:
F_Names L_Name Age a John Wick 22 b Romi Wilson 23 c Python Pandas 25
Example #4: Specify DataType of Column
# list of strings lst = [['John', 'Wick', 22], ['Romi', 'Wilson', 23], ['Python', 'Pandas', 25]] # Calling DataFrame constructor on list # with datatype df = pd.DataFrame(lst, columns =['F_Names', 'L_Name', 'Age'], dtype='float') print(df )
Output:
F_Names L_Name Age 0 John Wick 22.0 1 Romi Wilson 23.0 2 Python Pandas 25.0
Example #5: DataFrame form Multiple list (Using zip() function)
# import pandas as pd import pandas as pd # list of strings lst1 = ['Python', 'Pandas', 'is', 'best', 'Python', 'blog'] lst2 = [22, 23, 24, 25, 26, 27] # Calling DataFrame constructor on lists using zip() method df = pd.DataFrame(list(zip(lst1, lst2)), columns =['Name', 'val']) print(df )
Output:
Name val 0 Python 22 1 Pandas 23 2 is 24 3 best 25 4 Python 26 5 blog 27
Last Updated on May 10, 2020 by admin