Which plants are better for bees: native or non-native?
๐ Background
You work for the local government environment agency and have taken on a project about creating pollinator bee-friendly spaces. You can use both native and non-native plants to create these spaces and therefore need to ensure that you use the correct plants to optimize the environment for these bees.
The team has collected data on native and non-native plants and their effects on pollinator bees. Your task will be to analyze this data and provide recommendations on which plants create an optimized environment for pollinator bees.
๐พ The Data
You have assembled information on the plants and bees research in a file called plants_and_bees.csv. Each row represents a sample that was taken from a patch of land where the plant species were being studied.
| Column | Description |
|---|---|
sample_id | The ID number of the sample taken. |
bees_num | The total number of bee individuals in the sample. |
date | Date the sample was taken. |
season | Season during sample collection ("early.season" or "late.season"). |
site | Name of collection site. |
native_or_non | Whether the sample was from a native or non-native plot. |
sampling | The sampling method. |
plant_species | The name of the plant species the sample was taken from. None indicates the sample was taken from the air. |
time | The time the sample was taken. |
bee_species | The bee species in the sample. |
sex | The gender of the bee species. |
specialized_on | The plant genus the bee species preferred. |
parasitic | Whether or not the bee is parasitic (0:no, 1:yes). |
nesting | The bees nesting method. |
status | The status of the bee species. |
nonnative_bee | Whether the bee species is native or not (0:no, 1:yes). |
Source (data has been modified)
๐ช Challenge
Provide your agency with a report that covers the following:
- Which plants are preferred by native vs non-native bee species?
- A visualization of the distribution of bee and plant species across one of the samples.
- Select the top three plant species you would recommend to the agency to support native bees.
These are in a slightly altered order!
Predefining custom functions.
def top_plants(df, n: int = 3):
'''A function that selects and orders best plants for non-parasitic bees, including information about whether the plant is native or not.
Arguments:
df: the DataFrame with information about bees
Returns:
A dataframe containing the names and total bee counts for the top n species of plants and their nativity.
'''
# select the nonparasitic bee species and samples where the plant species is not none
non_parasitic = df[(df["parasitic"] == 0) & (df['plant_species']!= 'None' )]
# group the samples by plant species and sum up bee counts for every species
# sort the values in descending order
best_plants = non_parasitic.groupby("plant_species").agg({'count_per_species':'sum'}).sort_values('count_per_species',ascending=False)
# include info on whether the species is native or not
best_plants_and_kinds = best_plants.merge(df[['plant_species', 'native_or_non']].drop_duplicates(), on='plant_species', how='left')
# rename the columns
best_plants_and_kinds.columns = ['plant_species', 'total_bees', 'native_or_non']
return best_plants_and_kindsdef visualize_plants(df, title: str):
'''A function that makes it easier to generate seaborn plots for the given data about plants and bees.
Arguments:
df: the DataFrame with the information about top plants
title (str): a string to be used as the title of the plot
'''
# plot the plot
sns.barplot(y='plant_species', x='total_bees', data=df).set(xlabel='Number of bees', ylabel='Plant species', title=title)
# show the plot
plt.show()Importing the data and libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv("data/plants_and_bees.csv")
dataOne issue with the data is that every bee observation is its own entry, instead of there being a column with a count for a given species. First, that column has to be added, as bees_num cannot serve that purpose, being the total count of bees of different species in a sample.
# obtain counts per sample, plant species, and bee species
counts = data.groupby(['sample_id', 'plant_species', 'bee_species']).agg({'bee_species': 'count'})
# rename the column to avoid errors and conflicts
counts.columns = ['count_per_species']
# merge the counts into the data, drop doubles as initially the number of identical entries was an indication of how many
# individuals there were, and now that information is stored in a separate column
data = data.merge(counts, on=['sample_id', 'plant_species', 'bee_species']).drop_duplicates()
# display the data
dataA visualization of the distribution of bee and plant species across one of the samples.
# we need to select a sample that features some plant species
vis_candidates = data[data['plant_species'] != 'None']
# selecting the most diverse sample in terms of bee species
most_diverse_sample = vis_candidates.groupby('sample_id').agg({'bee_species':'count'}).sort_values('bee_species', ascending=False)
print('Top 1 most diverse sample:')
print(most_diverse_sample.head(1))# subsetting for just the best sample, subsetting relevant columns
best_sample = vis_candidates.set_index("sample_id").loc[17473][['count_per_species', 'plant_species', 'bee_species']]
best_sample# visualize the bee species per type of plant with an indication of their number
best_sample.plot(
kind='scatter',
y='bee_species',
x='plant_species',
xlabel='Bee species',
ylabel='Plant species',
legend=False,
title='Bee and plant species in sample 17473',
rot=45,
c='g',
s=best_sample['count_per_species']*25
)
plt.show()โ
โ