Saturday, September 21, 2024
Google search engine
HomeLanguagesCreating Pandas dataframe using list of lists

Creating Pandas dataframe using list of lists

Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object.
Pandas DataFrame can be created in multiple ways. Let’s discuss how to create a Pandas dataframe using list of lists.

Using pd.DataFrame() function

Example #1: 

In this example, we will create a list of lists and then pass it to the Pandas DataFrame function. Also, we will add the parameter of columns which will contain the column names.

Python3




# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [['Geeks', 10], ['for', 15], ['Lazyroar', 20]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
 
# print dataframe.
print(df)


Output:

    Name  Age
0 Geeks 10
1 for 15
2 Lazyroar 20

  
Example #2:

Let’s see another example with the same implementation as above.

Python3




# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [['DS', 'Linked_list', 10], ['DS', 'Stack', 9], ['DS', 'Queue', 7],
        ['Algo', 'Greedy', 8], ['Algo', 'DP', 6], ['Algo', 'BackTrack', 5], ]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Category', 'Name', 'Marks'])
 
# print dataframe.
print(df)


Output:

  Category         Name  Marks
0 DS Linked_list 10
1 DS Stack 9
2 DS Queue 7
3 Algo Greedy 8
4 Algo DP 6
5 Algo BackTrack 5

Defining column names using Dataframe.columns() function 

Doing some operations on dataframe like transpose. And also defining the Dataframe without column parameters and using df.columns() for the same.

Python3




# Import pandas library
import pandas as pd
 
# initialize list of lists
data = [[1, 5, 10], [2, 6, 9], [3, 7, 8]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data)
 
# specifying column names
df.columns = ['Col_1', 'Col_2', 'Col_3']
 
# print dataframe.
print(df, "\n")
 
# transpose of dataframe
df = df.transpose()
print("Transpose of above dataframe is-\n", df)


Output:

   Col_1  Col_2  Col_3
0 1 5 10
1 2 6 9
2 3 7 8
Transpose of above dataframe is-
0 1 2
Col_1 1 2 3
Col_2 5 6 7
Col_3 10 9 8

RELATED ARTICLES

Most Popular

Recent Comments