5

How to append rows to a DataFrame in Pandas?

 1 year ago
source link: https://thispointer.com/how-to-append-rows-to-a-dataframe-in-pandas/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In this article, we will discuss different ways to create a Pandas DataFrame and append one row at a time in it.

Table Of Contents

What is a DataFrame?

Pandas DataFrame is two dimensional data structure , potentially heterogeneous tabular data structure with three elements : data, rows and columns.

How to Create DataFrame

There are three different ways to create DataFrame in Pandas. First, we will discuss different ways to create Pandas DataFrame, then we will discuss foe to append one row at a time in it.

Examples of Creating DataFrame in pandas

Advertisements

Create Empty DataFrame

Write pandas script to create empty dataframe

import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
import pandas as pd  

# Calling DataFrame constructor  
df = pd.DataFrame()  

print(df)

In the above script, we have imported pandas library and call default constructor to create an empty dataframe.

Output

Empty DataFrame
Columns: []
Index: []
Empty DataFrame
Columns: []
Index: []

Create DataFrame from list with two columns

import pandas as pd
# initialize list with two columns
data = [['Reema', 10],
['Rekha', 15],
['Jaya', 14]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
# print dataframe.
print(df)
import pandas as pd

# initialize list with two columns
data = [['Reema', 10],
        ['Rekha', 15],
        ['Jaya', 14]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# print dataframe.
print(df)

In the above script , we have imported pandas library using the import keyword. Then created a list with two columns name and age. To create a DataFrame from a list we have used pandas dataframe constructor with two parameters.

Output

Name Age
0 reema 10
1 Rekha 15
2 jaya 14
Name  Age
0  reema   10
1  Rekha   15
2   jaya   14

Create a Pandas dataframe from a dictionary

import pandas as pd
# Create dictionary with two columns
d = {'rollno': [1, 2],
# Create the pandas DataFrame
df = pd.DataFrame(data=d)
# print dataframe.
print(df)
import pandas as pd

# Create dictionary with two columns
d = {'rollno': [1, 2],
     'Email': ['[email protected]', '[email protected]'] }

# Create the pandas DataFrame
df = pd.DataFrame(data=d)

# print dataframe.
print(df)

In the above script , we have imported pandas library with import keyword, and created a dictionary with two columns and two rows. To create dataFrame from dictionary, pandas dataframe constructor with one argument of dictionary is used.

Output

rollno          Email
0       1  [email protected]
1       2  [email protected]

Create Pandas DataFrame from NumPy ndarray

import pandas as pd
import numpy as np
# Create the pandas DataFrame
df = pd.DataFrame(np.array([[10, 'Reema', 'Surat'],
[20, 'Rekha', 'Surat'],
[30, 'Jaya', 'Vapi']]),
columns=['Rollno', 'Name', 'City'])
# print dataframe.
print(df)
import pandas as pd
import numpy as np

# Create the pandas DataFrame

df = pd.DataFrame(np.array([[10, 'Reema', 'Surat'],
                            [20, 'Rekha', 'Surat'],
                            [30, 'Jaya', 'Vapi']]),
                 columns=['Rollno', 'Name', 'City'])

# print dataframe.
print(df)

Output

Rollno Name City
0 10 Reema Surat
1 20 Rekha Surat
2 30 Jaya Vapi
Rollno   Name   City
0     10  Reema  Surat
1     20  Rekha  Surat
2     30   Jaya   Vapi

In the above script, first we have imported two libraries numpy and pandas. Then pandas dataframe is created with three columns rollno, name and city and also three rows.

Create DataFrame from dataclass

import pandas as pd
from dataclasses import make_dataclass
Point = make_dataclass("Point", [("Rollno", int), ("Name", str)])
df = pd.DataFrame( [Point(10, 'Reema'),
Point(20, 'Rekha'),
Point(30, 'Jaya')])
# print dataframe
print(df)
import pandas as pd
from dataclasses import make_dataclass

Point = make_dataclass("Point", [("Rollno", int), ("Name", str)])

df = pd.DataFrame( [Point(10, 'Reema'),
                    Point(20, 'Rekha'),
                    Point(30, 'Jaya')])

# print dataframe
print(df)

Output

Rollno Name
0 10 Reema
1 20 Rekha
2 30 Jaya
   Rollno   Name
0      10  Reema
1      20  Rekha
2      30   Jaya

In the above script, make_dataclass method is used to create dataframe from dataclass with two columns , and also add rows with point

Append one row at a time in Pandas DataFrame

We can add a new row in existing DataFrame of Pandas using verious methods. Let’s discuss them one by one,

Append a row using DataFrame.loc method

DataFrame.loc[] method will appned a row in the bottom of the dataframe

Example of append a row in DataFrame using DataFrame.loc method

A script to append a row in dataframe of three columns name, rollno and marks using dataframe.loc method,

import pandas as pd
# Import numpy package
import numpy as np
# Create dataFrame from dictionary
dict = {'Name':['Reema', 'Rekha', 'Jaya', 'susma'],
'Rollno':[1, 2, 3, 4],
'Marks':[83, 99, 84, 76] }
# Create the pandas DataFrame
df = pd.DataFrame(dict)
# print dataframe.
print(df)
# Append a new row in DataFrame
df.loc[len(df.index)] = ['Meena', 5, 93]
print(df)
import pandas as pd

# Import numpy package
import numpy as np

# Create dataFrame from dictionary
dict = {'Name':['Reema', 'Rekha', 'Jaya', 'susma'],
        'Rollno':[1, 2, 3, 4],
        'Marks':[83, 99, 84, 76] }

# Create the pandas DataFrame

df = pd.DataFrame(dict)

# print dataframe.
print(df)

# Append a new row in DataFrame
df.loc[len(df.index)] = ['Meena', 5, 93] 

print(df)

Output

Name Rollno Marks
0 Reema 1 83
1 Rekha 2 99
2 Jaya 3 84
3 susma 4 76
Name Rollno Marks
0 Reema 1 83
1 Rekha 2 99
2 Jaya 3 84
3 susma 4 76
4 Meena 5 93
Name  Rollno  Marks
0  Reema       1     83
1  Rekha       2     99
2   Jaya       3     84
3  susma       4     76

Name  Rollno  Marks
0  Reema       1     83
1  Rekha       2     99
2   Jaya       3     84
3  susma       4     76
4  Meena       5     93

In the above script , we have imported two libraries pandas and numpy. To create dataframe, we have created dictionary with three columns name, rollno and marks. To create dataframe from dictionary pandas.DataFrame() method is used. To append new row into already created dataframe dataframe df.loc method is applied with dataframe with length position and new row values.

Append a row to DataFrame using append() method

DataFrame.append() method is use to add a new row in the DataFrame using lists.

A script to create dataframe and append a row using dataframe.append() method is as follows,

import pandas as pd
import numpy as np
# Create dataFrame from dictionary
dict = {'Name':['Reema', 'Rekha', 'Jaya', 'susma'],
'Rollno':[1, 2, 3, 4],
'Marks':[83, 99, 84, 76] }
# Create the pandas DataFrame
df = pd.DataFrame(dict)
# print dataframe.
print(df)
print()
# Append a new row in DataFrame
df2 = { 'Name': 'Meera',
'Rollno': 5,
'Marks': 93}
# Add a row to DataFrame
df = df.append(df2, ignore_index = True)
print(df)
import pandas as pd
import numpy as np

# Create dataFrame from dictionary
dict = {'Name':['Reema', 'Rekha', 'Jaya', 'susma'],
        'Rollno':[1, 2, 3, 4],
        'Marks':[83, 99, 84, 76] }


# Create the pandas DataFrame
df = pd.DataFrame(dict)

# print dataframe.
print(df)
print()

# Append a new row in DataFrame
df2 = { 'Name': 'Meera',
        'Rollno': 5,
        'Marks': 93}

# Add a row to DataFrame
df = df.append(df2, ignore_index = True) 

print(df)

In the above script , first we have imported two libraries pandas and numpy , create dictionary with three columns and four rows , than create dataframe from dictionary
to append a row another dataframe is created and using dataframe.append method import newly created dataframe into existing dataframe

Output

Name Rollno Marks
0 Reema 1 83
1 Rekha 2 99
2 Jaya 3 84
3 susma 4 76
Name Rollno Marks
0 Reema 1 83
1 Rekha 2 99
2 Jaya 3 84
3 susma 4 76
4 Meera 5 93
Name  Rollno  Marks
0  Reema       1     83
1  Rekha       2     99
2   Jaya       3     84
3  susma       4     76

Name  Rollno  Marks
0  Reema       1     83
1  Rekha       2     99
2   Jaya       3     84
3  susma       4     76
4  Meera       5     93

Summary

In this article of we learned how to create a Pandas Dataframe and append one row at a time. We have discussed what is dataframe in pandas, the syntax of dataframe, how to create a dataframe. What are the ways to append a new row in existing dataframe in pandas, and also explained each methods to append a row with examples.

Pandas Tutorials -Learn Data Analysis with Python

 

 

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK