Predictive Hacks

Tidyr’s nest function in Pandas

import pandas as pd
import seaborn
#loading the iris dataset
iris = seaborn.load_dataset("iris")
iris.head(3)
   sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
#The pandas "Nest" function
df=iris.groupby("species").apply(lambda x:dict(x))
Species
setosa        {'Sepal.Length': [5.1, 4.9, 4.7, 4.6, 5.0, 5.4...
versicolor    {'Sepal.Length': [7.0, 6.4, 6.9, 5.5, 6.5, 5.7...
virginica     {'Sepal.Length': [6.3, 5.8, 7.1, 6.3, 6.5, 7.6...
#To access one of the Species:
pd.DataFrame(df['versicolor'])
     sepal_length  sepal_width  petal_length  petal_width     species
100           7.0          3.2           4.7          1.4  versicolor
101           6.4          3.2           4.5          1.5  versicolor
102           6.9          3.1           4.9          1.5  versicolor

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.