Hello, students! Today, we're exploring the pandas DataFrame, a powerhouse structure in data analysis with Python. We'll contrast it with NumPy arrays and teach you how to build a DataFrame. Additionally, we'll delve into its integral parts and data types.
The pandas library is Python's solution for tabular data operations, packing more punch for data analysis than NumPy, which is skewed towards numerical computations. Pandas houses two fundamental data structures: the Series (1D) and the DataFrame (2D). Often, the DataFrame is the go-to choice. Let's start by importing pandas:
Here, pd serves as a standard alias for pandas.
Building a DataFrame in pandas is straightforward. It can be created from a dictionary, list, or NumPy array. Here's an example of creating a DataFrame from a dictionary:
In the student_data dictionary, each (key, value) pair becomes a DataFrame column. The DataFrame automatically assigns an index (0-2) to each row, but we can also specify our own if we choose to do so.
Adding a new column to an existing DataFrame is straightforward: just like with dictionary, simply refer to a new key and assign an array to it. Let's add information about student's grades to our data:
The 'Grade' column has been successfully added to the DataFrame.
A DataFrame consists of three components: data, index, and columns. Pandas neatly organize data into rows and columns — each row is a record, and each column is a feature (such as Name, Age, or Grade). The index, much like the index of a book, aids in data location. Columns serve as labels for the features in our data. Let's analyze these components with our student data:
Our dataset contains row labels (index) from 0 to 2 and column labels (columns) of 'Name', 'Age', and 'Grade'.
