Python offers its users a vast selection of built-in and installable libraries and packages, allowing developers to access functionalities they might need for their programs. These libraries and packages can streamline the development process and reduce the time required to code efficient solutions.
We can also rename the packages locally for our convenience, which we will cover in this Answer.
For our example, we'll see how to rename the pandas
package. First, let's see how we would typically import this package:
import pandasurl = 'https://raw.githubusercontent.com/PacktPublishing/Mastering-spaCy/main/Chapter10/data/restaurants.json'dataset = pandas.read_json(url, encoding = 'utf-8')print(dataset.head())
In the code above:
Line 1: We import the pandas
library.
Line 3: We create a variable called url
which holds the URL of a dataset we wish to access.
Line 4: We use the pandas.read_json()
function to load the dataset into an aptly named variable dataset
.
Line 5: We call the dataset.head()
function and print the first five rows from the dataset.
Now let's see how we can rename the package and then use the renamed package. To rename a package, we can use the as
keyword in Python as shown below:
import pandas as pd
As shown above, we can use pd
instead of pandas
when we want to use functions available in the pandas
library. Let's see this in action with the previous example:
import pandas as pdurl = 'https://raw.githubusercontent.com/PacktPublishing/Mastering-spaCy/main/Chapter10/data/restaurants.json'dataset = pd.read_json(url, encoding = 'utf-8')print(dataset.head())
The code largely remains the same as before and will have the same output. The only differences we have are on Line 1 and Line 4:
Line 1: We simply add the as
keyword that tells the interpreter that pd
will now refer to the pandas
library.
Line 4: We replace the pandas.read_json()
with pd.read_json()
as pd
will always refer to pandas
in our code.
Free Resources