Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Adding new Rows | Basics of Dataframes
Pandas: First Steps
course content

Contenu du cours

Pandas: First Steps

Pandas: First Steps

1. Getting Started
2. Basics of Dataframes

book
Adding new Rows

You can add new rows to an existing DataFrame using the loc property.

js

The list [value1, value2, ...] must contain a value for all the columns otherwise the program will throw an error.

The loc property allows you to access data in a DataFrame using both numerical and custom indices. When used in an assignment statement, loc will create a new row if the specified index doesn't already exist.

1234567891011
import pandas as pd # Creating a simple DataFrame data = {'Name': ['Alice', 'Bob'], 'Age': [30, 25]} df = pd.DataFrame(data) # Adding a new row using loc df.loc[2] = ['Charlie', 28] # The DataFrame now includes the new row print(df)
copy

In the example above, the loc property is used to add a new row at index 2 with the values 'Charlie' and 28.

Instead of manually specifying a new index everytime, we can simply use the len method to get the length of the DataFrame and use it as the next index. This makes the process more efficient:

12345678910111213
import pandas as pd # Creating a simple DataFrame data = {'Name': ['Alice', 'Bob'], 'Age': [30, 25]} df = pd.DataFrame(data) # Adding multiple rows using loc df.loc[len(df)] = ['Charlie', 28] df.loc[len(df)] = ['David', 35] df.loc[len(df)] = ['Eva', 22] # The DataFrame now includes the new rows print(df)
copy

1. What happens if you try to assign a value to a row index that doesn’t exist in the DataFrame, using loc?

2. Which of the following is the correct syntax to add a new row to a DataFrame at the next available index?

3. In the following code, what will len(dataframe) return?

4. Consider the following code. After executing all the lines, what will the DataFrame look like?

question mark

What happens if you try to assign a value to a row index that doesn’t exist in the DataFrame, using loc?

Select the correct answer

question mark

Which of the following is the correct syntax to add a new row to a DataFrame at the next available index?

Select the correct answer

question mark

In the following code, what will len(dataframe) return?

Select the correct answer

question mark

Consider the following code. After executing all the lines, what will the DataFrame look like?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 8
Nous sommes désolés de vous informer que quelque chose s'est mal passé. Qu'est-il arrivé ?
some-alt