Зміст курсу
Pandas: First Steps
Pandas: First Steps
1. Getting Started
Introduction to PandasSeriesTask: Coffee Orders SeriesTask: Barista's Favorites CoffeesAccessing Elements from a SeriesTask: Drink of the HourTask - Signature DrinksTask: Mid-Morning SpecialsTask - Fetching the Mid-Shift DrinksOperations over SeriesTask: Modifying a single elementTask: Modifying the Entire SeriesTask: Modifying Part of a SeriesTask: Processing the Restock of Inventory
2. Basics of Dataframes
What is a DataFrame?Task: Creating a Table of Popular Coffee DrinksTask: Tracking Coffee Bean DeliveriesTask: Weekly Coffee Sales ReportAdding new ColumnsTask: Finding Total Sales Per DrinkTask: Calculating Total Sales RevenueAdding new RowsTask: Adding a New Employee to the Café TeamTask: Adding New Coffee Types to the Café Menu
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?
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 2. Розділ 8