I have a dataframe and I when I run my code it returns all Nan's instead of returning the counted value. I'm sure it's something simple but I can't figure it out. I'm trying to get a unique number of species in each location. I'd like the new column to output a count of species [2,2,1,1,2,2,1,1]
import pandas as pd
df = pd.DataFrame({
'ID': [1, 2, 3, 4, 5, 6, 7, 8],
'location': ['A', 'A', 'C', 'C', 'E', 'E', 'E', 'E'],
'Species': ['Cat', 'Cat', 'Dog', 'Cat', 'Cat', 'Cat', 'Dog', 'Bird'],
'Count': [2,2,2,2,4,4,4,4]
})
def abundance(data):
data["Abundance"] = data[data.Species.notnull()].groupby('location')['Species'].unique()
abundance(df)
print(df)
````````````````````
ID location Species Count Abundance
0 1 A Cat 2 NaN
1 2 A Cat 2 NaN
2 3 C Dog 2 NaN
3 4 C Cat 2 NaN
4 5 E Cat 4 NaN
5 6 E Cat 4 NaN
6 7 E Dog 4 NaN
7 8 E Bird 4 NaN