Contenu du cours
Pandas: First Steps
Pandas: First Steps
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.
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)
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:
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)
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?
Merci pour vos commentaires !