0% found this document useful (0 votes)
2 views16 pages

lec 16 pandas_continue

The document contains Python code that reads a CSV file of Pokémon data into a DataFrame using pandas. It performs various data manipulations, including calculating total stats, renaming columns, changing case for type names, and grouping Pokémon by their legendary status and generation. The DataFrame ultimately contains 800 Pokémon entries with various attributes such as type, health points, and stats.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

lec 16 pandas_continue

The document contains Python code that reads a CSV file of Pokémon data into a DataFrame using pandas. It performs various data manipulations, including calculating total stats, renaming columns, changing case for type names, and grouping Pokémon by their legendary status and generation. The DataFrame ultimately contains 800 Pokémon entries with various attributes such as type, health points, and stats.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

In [ ]: import pandas as pd

import numpy as np

In [2]: df=pd.read_csv('D:\\AEGIS\\Python\\pokemon.csv')

In [3]: df

Out[3]: Type Sp. Sp.


# Name Type 1 HP Attack Defense Speed G
2 Atk Def

0 1 Bulbasaur Grass Poison 45 49 49 65 65 45

1 2 Ivysaur Grass Poison 60 62 63 80 80 60

2 3 Venusaur Grass Poison 80 82 83 100 100 80

Mega
3 4 Grass Poison 80 100 123 122 120 80
Venusaur

4 5 Charmander Fire NaN 39 52 43 60 50 65

... ... ... ... ... ... ... ... ... ... ...

795 796 Diancie Rock Fairy 50 100 150 100 150 50

Mega
796 797 Rock Fairy 50 160 110 160 110 110
Diancie

Hoopa
797 798 Psychic Ghost 80 110 60 150 130 70
Confined

Hoopa
798 799 Psychic Dark 80 160 60 170 130 80
Unbound

799 800 Volcanion Fire Water 80 110 120 130 90 70

800 rows × 12 columns

In [4]: df['Total']=df['HP']+df['Attack']+df['Defense']+df['Sp. Atk']+df['Sp. Def']+

In [5]: df
Out[5]: Type Sp. Sp.
# Name Type 1 HP Attack Defense Speed G
2 Atk Def

0 1 Bulbasaur Grass Poison 45 49 49 65 65 45

1 2 Ivysaur Grass Poison 60 62 63 80 80 60

2 3 Venusaur Grass Poison 80 82 83 100 100 80

Mega
3 4 Grass Poison 80 100 123 122 120 80
Venusaur

4 5 Charmander Fire NaN 39 52 43 60 50 65

... ... ... ... ... ... ... ... ... ... ...

795 796 Diancie Rock Fairy 50 100 150 100 150 50

Mega
796 797 Rock Fairy 50 160 110 160 110 110
Diancie

Hoopa
797 798 Psychic Ghost 80 110 60 150 130 70
Confined

Hoopa
798 799 Psychic Dark 80 160 60 170 130 80
Unbound

799 800 Volcanion Fire Water 80 110 120 130 90 70

800 rows × 13 columns

In [6]: df.drop(['#'],inplace=True,axis=1)

In [7]: df.rename(columns={'HP':'Health Points'},inplace=True)

In [8]: df=df.set_index('Name')

In [9]: df
Out[9]: Type Health Sp. Sp.
Type 1 Attack Defense Speed Gener
2 Points Atk Def

Name

Bulbasaur Grass Poison 45 49 49 65 65 45

Ivysaur Grass Poison 60 62 63 80 80 60

Venusaur Grass Poison 80 82 83 100 100 80

Mega
Grass Poison 80 100 123 122 120 80
Venusaur

Charmander Fire NaN 39 52 43 60 50 65

... ... ... ... ... ... ... ... ...

Diancie Rock Fairy 50 100 150 100 150 50

Mega
Rock Fairy 50 160 110 160 110 110
Diancie

Hoopa
Psychic Ghost 80 110 60 150 130 70
Confined

Hoopa
Psychic Dark 80 160 60 170 130 80
Unbound

Volcanion Fire Water 80 110 120 130 90 70

800 rows × 11 columns

Q. Find how many Legendary


Pokemons which have a single
type(Type 1 present and Type 2
absent)
In [10]: true_legendary=df[df['Legendary']==True]
x=true_legendary['Type 2'].isnull().sum()
print('No of Legendary pokemons which have a single type(type 1 present and

No of Legendary pokemons which have a single type(type 1 present and type 2


absent) are 25

In [11]: z=df[(df['Legendary']==True) & (df['Type 2'].isnull())]


len(z)

Out[11]: 25

Q. Convert all Type 1 to lower case


In [12]: lower_type1=df['Type 1'].str.lower()
lower_type1

Out[12]: Name
Bulbasaur grass
Ivysaur grass
Venusaur grass
Mega Venusaur grass
Charmander fire
...
Diancie rock
Mega Diancie rock
Hoopa Confined psychic
Hoopa Unbound psychic
Volcanion fire
Name: Type 1, Length: 800, dtype: object

In [13]: upper_type1=df['Type 1'].str.upper()


upper_type1

Out[13]: Name
Bulbasaur GRASS
Ivysaur GRASS
Venusaur GRASS
Mega Venusaur GRASS
Charmander FIRE
...
Diancie ROCK
Mega Diancie ROCK
Hoopa Confined PSYCHIC
Hoopa Unbound PSYCHIC
Volcanion FIRE
Name: Type 1, Length: 800, dtype: object

Apply()
In [14]: df['Type 1'].apply(lambda x:x.lower())

Out[14]: Name
Bulbasaur grass
Ivysaur grass
Venusaur grass
Mega Venusaur grass
Charmander fire
...
Diancie rock
Mega Diancie rock
Hoopa Confined psychic
Hoopa Unbound psychic
Volcanion fire
Name: Type 1, Length: 800, dtype: object

In [15]: isinstance('abc',str)
Out[15]: True

In [16]: isinstance(10,str)

Out[16]: False

In [17]: isinstance(10,int)

Out[17]: True

Q. If type 2 present change to upper


case else replace by None
In [18]: y=df['Type 2'].apply(lambda x:x.upper() if isinstance(x,str) else None)
y

Out[18]: Name
Bulbasaur POISON
Ivysaur POISON
Venusaur POISON
Mega Venusaur POISON
Charmander None
...
Diancie FAIRY
Mega Diancie FAIRY
Hoopa Confined GHOST
Hoopa Unbound DARK
Volcanion WATER
Name: Type 2, Length: 800, dtype: object

In [19]: y=df['Type 2'].fillna('None').str.upper()


y

Out[19]: Name
Bulbasaur POISON
Ivysaur POISON
Venusaur POISON
Mega Venusaur POISON
Charmander NONE
...
Diancie FAIRY
Mega Diancie FAIRY
Hoopa Confined GHOST
Hoopa Unbound DARK
Volcanion WATER
Name: Type 2, Length: 800, dtype: object

Groupby()
In [20]: df.head()
Out[20]: Type Type Health Sp. Sp.
Attack Defense Speed Generat
1 2 Points Atk Def

Name

Bulbasaur Grass Poison 45 49 49 65 65 45

Ivysaur Grass Poison 60 62 63 80 80 60

Venusaur Grass Poison 80 82 83 100 100 80

Mega
Grass Poison 80 100 123 122 120 80
Venusaur

Charmander Fire NaN 39 52 43 60 50 65

In [21]: df.groupby('Legendary').groups #show different groups as key value pair

Out[21]: {False: ['Bulbasaur', 'Ivysaur', 'Venusaur', 'Mega Venusaur', 'Charmander',


'Charmeleon', 'Charizard', 'Mega Charizard X', 'Mega Charizard Y', 'Squirtl
e', 'Wartortle', 'Blastoise', 'Mega Blastoise', 'Caterpie', 'Metapod', 'But
terfree', 'Weedle', 'Kakuna', 'Beedrill', 'Mega Beedrill', 'Pidgey', 'Pidge
otto', 'Pidgeot', 'Mega Pidgeot', 'Rattata', 'Raticate', 'Spearow', 'Fearo
w', 'Ekans', 'Arbok', 'Pikachu', 'Raichu', 'Sandshrew', 'Sandslash', 'Nidor
an♀', 'Nidorina', 'Nidoqueen', 'Nidoran♂', 'Nidorino', 'Nidoking', 'Clefair
y', 'Clefable', 'Vulpix', 'Ninetales', 'Jigglypuff', 'Wigglytuff', 'Zubat',
'Golbat', 'Oddish', 'Gloom', 'Vileplume', 'Paras', 'Parasect', 'Venonat',
'Venomoth', 'Diglett', 'Dugtrio', 'Meowth', 'Persian', 'Psyduck', 'Golduc
k', 'Mankey', nan, 'Growlithe', 'Arcanine', 'Poliwag', 'Poliwhirl', 'Poliwr
ath', 'Abra', 'Kadabra', 'Alakazam', 'Mega Alakazam', 'Machop', 'Machoke',
'Machamp', 'Bellsprout', 'Weepinbell', 'Victreebel', 'Tentacool', 'Tentacru
el', 'Geodude', 'Graveler', 'Golem', 'Ponyta', 'Rapidash', 'Slowpoke', 'Slo
wbro', 'Mega Slowbro', 'Magnemite', 'Magneton', 'Farfetch'd', 'Doduo', 'Dod
rio', 'Seel', 'Dewgong', 'Grimer', 'Muk', 'Shellder', 'Cloyster', 'Gastly',
...], True: ['Articuno', 'Zapdos', 'Moltres', 'Mewtwo', 'Mega Mewtwo X', 'M
ega Mewtwo Y', 'Raikou', 'Entei', 'Suicune', 'Lugia', 'Ho-oh', 'Regirock',
'Regice', 'Registeel', 'Latias', 'Mega Latias', 'Latios', 'Mega Latios', 'K
yogre', 'Primal Kyogre', 'Groudon', 'Primal Groudon', 'Rayquaza', 'Mega Ray
quaza', 'Jirachi', 'Deoxys Normal Forme', 'DeoxysAttack Forme', 'Deoxys Def
ense Forme', 'Deoxys Speed Forme', 'Uxie', 'Mesprit', 'Azelf', 'Dialga', 'P
alkia', 'Heatran', 'Regigigas', 'Giratina Altered Forme', 'Giratina Origin
Forme', 'Darkrai', 'Shaymin Land Forme', 'Shaymin Sky Forme', 'Arceus', 'Vi
ctini', 'Cobalion', 'Terrakion', 'Virizion', 'Tornadus Incarnate Forme', 'T
ornadus Therian Forme', 'Thundurus Incarnate Forme', 'Thundurus Therian For
me', 'Reshiram', 'Zekrom', 'Landorus Incarnate Forme', 'Landorus Therian Fo
rme', 'Kyurem', 'Kyurem Black Kyurem', 'Kyurem White Kyurem', 'Xerneas', 'Y
veltal', 'Zygarde Half Forme', 'Diancie', 'Mega Diancie', 'Hoopa Confined',
'Hoopa Unbound', 'Volcanion']}

In [22]: df.groupby('Generation').groups
Out[22]: {1: ['Bulbasaur', 'Ivysaur', 'Venusaur', 'Mega Venusaur', 'Charmander', 'Ch
armeleon', 'Charizard', 'Mega Charizard X', 'Mega Charizard Y', 'Squirtle',
'Wartortle', 'Blastoise', 'Mega Blastoise', 'Caterpie', 'Metapod', 'Butterf
ree', 'Weedle', 'Kakuna', 'Beedrill', 'Mega Beedrill', 'Pidgey', 'Pidgeott
o', 'Pidgeot', 'Mega Pidgeot', 'Rattata', 'Raticate', 'Spearow', 'Fearow',
'Ekans', 'Arbok', 'Pikachu', 'Raichu', 'Sandshrew', 'Sandslash', 'Nidoran
♀', 'Nidorina', 'Nidoqueen', 'Nidoran♂', 'Nidorino', 'Nidoking', 'Clefair
y', 'Clefable', 'Vulpix', 'Ninetales', 'Jigglypuff', 'Wigglytuff', 'Zubat',
'Golbat', 'Oddish', 'Gloom', 'Vileplume', 'Paras', 'Parasect', 'Venonat',
'Venomoth', 'Diglett', 'Dugtrio', 'Meowth', 'Persian', 'Psyduck', 'Golduc
k', 'Mankey', nan, 'Growlithe', 'Arcanine', 'Poliwag', 'Poliwhirl', 'Poliwr
ath', 'Abra', 'Kadabra', 'Alakazam', 'Mega Alakazam', 'Machop', 'Machoke',
'Machamp', 'Bellsprout', 'Weepinbell', 'Victreebel', 'Tentacool', 'Tentacru
el', 'Geodude', 'Graveler', 'Golem', 'Ponyta', 'Rapidash', 'Slowpoke', 'Slo
wbro', 'Mega Slowbro', 'Magnemite', 'Magneton', 'Farfetch'd', 'Doduo', 'Dod
rio', 'Seel', 'Dewgong', 'Grimer', 'Muk', 'Shellder', 'Cloyster', 'Gastly',
...], 2: ['Chikorita', 'Bayleef', 'Meganium', 'Cyndaquil', 'Quilava', 'Typh
losion', 'Totodile', 'Croconaw', 'Feraligatr', 'Sentret', 'Furret', 'Hootho
ot', 'Noctowl', 'Ledyba', 'Ledian', 'Spinarak', 'Ariados', 'Crobat', 'Chinc
hou', 'Lanturn', 'Pichu', 'Cleffa', 'Igglybuff', 'Togepi', 'Togetic', 'Nat
u', 'Xatu', 'Mareep', 'Flaaffy', 'Ampharos', 'Mega Ampharos', 'Bellossom',
'Marill', 'Azumarill', 'Sudowoodo', 'Politoed', 'Hoppip', 'Skiploom', 'Jump
luff', 'Aipom', 'Sunkern', 'Sunflora', 'Yanma', 'Wooper', 'Quagsire', 'Espe
on', 'Umbreon', 'Murkrow', 'Slowking', 'Misdreavus', 'Unown', 'Wobbuffet',
'Girafarig', 'Pineco', 'Forretress', 'Dunsparce', 'Gligar', 'Steelix', 'Meg
a Steelix', 'Snubbull', 'Granbull', 'Qwilfish', 'Scizor', 'Mega Scizor', 'S
huckle', 'Heracross', 'Mega Heracross', 'Sneasel', 'Teddiursa', 'Ursaring',
'Slugma', 'Magcargo', 'Swinub', 'Piloswine', 'Corsola', 'Remoraid', 'Octill
ery', 'Delibird', 'Mantine', 'Skarmory', 'Houndour', 'Houndoom', 'Mega Houn
doom', 'Kingdra', 'Phanpy', 'Donphan', 'Porygon2', 'Stantler', 'Smeargle',
'Tyrogue', 'Hitmontop', 'Smoochum', 'Elekid', 'Magby', 'Miltank', 'Blisse
y', 'Raikou', 'Entei', 'Suicune', 'Larvitar', ...], 3: ['Treecko', 'Grovyl
e', 'Sceptile', 'Mega Sceptile', 'Torchic', 'Combusken', 'Blaziken', 'Mega
Blaziken', 'Mudkip', 'Marshtomp', 'Swampert', 'Mega Swampert', 'Poochyena',
'Mightyena', 'Zigzagoon', 'Linoone', 'Wurmple', 'Silcoon', 'Beautifly', 'Ca
scoon', 'Dustox', 'Lotad', 'Lombre', 'Ludicolo', 'Seedot', 'Nuzleaf', 'Shif
try', 'Taillow', 'Swellow', 'Wingull', 'Pelipper', 'Ralts', 'Kirlia', 'Gard
evoir', 'Mega Gardevoir', 'Surskit', 'Masquerain', 'Shroomish', 'Breloom',
'Slakoth', 'Vigoroth', 'Slaking', 'Nincada', 'Ninjask', 'Shedinja', 'Whismu
r', 'Loudred', 'Exploud', 'Makuhita', 'Hariyama', 'Azurill', 'Nosepass', 'S
kitty', 'Delcatty', 'Sableye', 'Mega Sableye', 'Mawile', 'Mega Mawile', 'Ar
on', 'Lairon', 'Aggron', 'Mega Aggron', 'Meditite', 'Medicham', 'Mega Medic
ham', 'Electrike', 'Manectric', 'Mega Manectric', 'Plusle', 'Minun', 'Volbe
at', 'Illumise', 'Roselia', 'Gulpin', 'Swalot', 'Carvanha', 'Sharpedo', 'Me
ga Sharpedo', 'Wailmer', 'Wailord', 'Numel', 'Camerupt', 'Mega Camerupt',
'Torkoal', 'Spoink', 'Grumpig', 'Spinda', 'Trapinch', 'Vibrava', 'Flygon',
'Cacnea', 'Cacturne', 'Swablu', 'Altaria', 'Mega Altaria', 'Zangoose', 'Sev
iper', 'Lunatone', 'Solrock', 'Barboach', ...], 4: ['Turtwig', 'Grotle', 'T
orterra', 'Chimchar', 'Monferno', 'Infernape', 'Piplup', 'Prinplup', 'Empol
eon', 'Starly', 'Staravia', 'Staraptor', 'Bidoof', 'Bibarel', 'Kricketot',
'Kricketune', 'Shinx', 'Luxio', 'Luxray', 'Budew', 'Roserade', 'Cranidos',
'Rampardos', 'Shieldon', 'Bastiodon', 'Burmy', 'Wormadam Plant Cloak', 'Wor
madam Sandy Cloak', 'Wormadam Trash Cloak', 'Mothim', 'Combee', 'Vespique
n', 'Pachirisu', 'Buizel', 'Floatzel', 'Cherubi', 'Cherrim', 'Shellos', 'Ga
strodon', 'Ambipom', 'Drifloon', 'Drifblim', 'Buneary', 'Lopunny', 'Mega Lo
punny', 'Mismagius', 'Honchkrow', 'Glameow', 'Purugly', 'Chingling', 'Stunk
y', 'Skuntank', 'Bronzor', 'Bronzong', 'Bonsly', 'Mime Jr.', 'Happiny', 'Ch
atot', 'Spiritomb', 'Gible', 'Gabite', 'Garchomp', 'Mega Garchomp', 'Munchl
ax', 'Riolu', 'Lucario', 'Mega Lucario', 'Hippopotas', 'Hippowdon', 'Skorup
i', 'Drapion', 'Croagunk', 'Toxicroak', 'Carnivine', 'Finneon', 'Lumineon',
'Mantyke', 'Snover', 'Abomasnow', 'Mega Abomasnow', 'Weavile', 'Magnezone',
'Lickilicky', 'Rhyperior', 'Tangrowth', 'Electivire', 'Magmortar', 'Togekis
s', 'Yanmega', 'Leafeon', 'Glaceon', 'Gliscor', 'Mamoswine', 'Porygon-Z',
'Gallade', 'Mega Gallade', 'Probopass', 'Dusknoir', 'Froslass', 'Rotom',
...], 5: ['Victini', 'Snivy', 'Servine', 'Serperior', 'Tepig', 'Pignite',
'Emboar', 'Oshawott', 'Dewott', 'Samurott', 'Patrat', 'Watchog', 'Lillipu
p', 'Herdier', 'Stoutland', 'Purrloin', 'Liepard', 'Pansage', 'Simisage',
'Pansear', 'Simisear', 'Panpour', 'Simipour', 'Munna', 'Musharna', 'Pidov
e', 'Tranquill', 'Unfezant', 'Blitzle', 'Zebstrika', 'Roggenrola', 'Boldor
e', 'Gigalith', 'Woobat', 'Swoobat', 'Drilbur', 'Excadrill', 'Audino', 'Meg
a Audino', 'Timburr', 'Gurdurr', 'Conkeldurr', 'Tympole', 'Palpitoad', 'Sei
smitoad', 'Throh', 'Sawk', 'Sewaddle', 'Swadloon', 'Leavanny', 'Venipede',
'Whirlipede', 'Scolipede', 'Cottonee', 'Whimsicott', 'Petilil', 'Lilligan
t', 'Basculin', 'Sandile', 'Krokorok', 'Krookodile', 'Darumaka', 'Darmanita
n Standard Mode', 'Darmanitan Zen Mode', 'Maractus', 'Dwebble', 'Crustle',
'Scraggy', 'Scrafty', 'Sigilyph', 'Yamask', 'Cofagrigus', 'Tirtouga', 'Carr
acosta', 'Archen', 'Archeops', 'Trubbish', 'Garbodor', 'Zorua', 'Zoroark',
'Minccino', 'Cinccino', 'Gothita', 'Gothorita', 'Gothitelle', 'Solosis', 'D
uosion', 'Reuniclus', 'Ducklett', 'Swanna', 'Vanillite', 'Vanillish', 'Vani
lluxe', 'Deerling', 'Sawsbuck', 'Emolga', 'Karrablast', 'Escavalier', 'Foon
gus', 'Amoonguss', ...], 6: ['Chespin', 'Quilladin', 'Chesnaught', 'Fenneki
n', 'Braixen', 'Delphox', 'Froakie', 'Frogadier', 'Greninja', 'Bunnelby',
'Diggersby', 'Fletchling', 'Fletchinder', 'Talonflame', 'Scatterbug', 'Spew
pa', 'Vivillon', 'Litleo', 'Pyroar', 'Flabébé', 'Floette', 'Florges', 'Skid
do', 'Gogoat', 'Pancham', 'Pangoro', 'Furfrou', 'Espurr', 'Meowstic Male',
'Meowstic Female', 'Honedge', 'Doublade', 'Aegislash Blade Forme', 'Aegisla
sh Shield Forme', 'Spritzee', 'Aromatisse', 'Swirlix', 'Slurpuff', 'Inkay',
'Malamar', 'Binacle', 'Barbaracle', 'Skrelp', 'Dragalge', 'Clauncher', 'Cla
witzer', 'Helioptile', 'Heliolisk', 'Tyrunt', 'Tyrantrum', 'Amaura', 'Auror
us', 'Sylveon', 'Hawlucha', 'Dedenne', 'Carbink', 'Goomy', 'Sliggoo', 'Good
ra', 'Klefki', 'Phantump', 'Trevenant', 'Pumpkaboo Average Size', 'Pumpkabo
o Small Size', 'Pumpkaboo Large Size', 'Pumpkaboo Super Size', 'Gourgeist A
verage Size', 'Gourgeist Small Size', 'Gourgeist Large Size', 'Gourgeist Su
per Size', 'Bergmite', 'Avalugg', 'Noibat', 'Noivern', 'Xerneas', 'Yvelta
l', 'Zygarde Half Forme', 'Diancie', 'Mega Diancie', 'Hoopa Confined', 'Hoo
pa Unbound', 'Volcanion']}

In [23]: df.groupby(['Generation','Type 1']).groups


Out[23]: {(1, 'Bug'): ['Caterpie', 'Metapod', 'Butterfree', 'Weedle', 'Kakuna', 'Bee
drill', 'Mega Beedrill', 'Paras', 'Parasect', 'Venonat', 'Venomoth', 'Scyth
er', 'Pinsir', 'Mega Pinsir'], (1, 'Dragon'): ['Dratini', 'Dragonair', 'Dra
gonite'], (1, 'Electric'): ['Pikachu', 'Raichu', 'Magnemite', 'Magneton',
'Voltorb', 'Electrode', 'Electabuzz', 'Jolteon', 'Zapdos'], (1, 'Fairy'):
['Clefairy', 'Clefable'], (1, 'Fighting'): ['Mankey', nan, 'Machop', 'Macho
ke', 'Machamp', 'Hitmonlee', 'Hitmonchan'], (1, 'Fire'): ['Charmander', 'Ch
armeleon', 'Charizard', 'Mega Charizard X', 'Mega Charizard Y', 'Vulpix',
'Ninetales', 'Growlithe', 'Arcanine', 'Ponyta', 'Rapidash', 'Magmar', 'Flar
eon', 'Moltres'], (1, 'Ghost'): ['Gastly', 'Haunter', 'Gengar', 'Mega Genga
r'], (1, 'Grass'): ['Bulbasaur', 'Ivysaur', 'Venusaur', 'Mega Venusaur', 'O
ddish', 'Gloom', 'Vileplume', 'Bellsprout', 'Weepinbell', 'Victreebel', 'Ex
eggcute', 'Exeggutor', 'Tangela'], (1, 'Ground'): ['Sandshrew', 'Sandslas
h', 'Diglett', 'Dugtrio', 'Cubone', 'Marowak', 'Rhyhorn', 'Rhydon'], (1, 'I
ce'): ['Jynx', 'Articuno'], (1, 'Normal'): ['Pidgey', 'Pidgeotto', 'Pidgeo
t', 'Mega Pidgeot', 'Rattata', 'Raticate', 'Spearow', 'Fearow', 'Jigglypuf
f', 'Wigglytuff', 'Meowth', 'Persian', 'Farfetch'd', 'Doduo', 'Dodrio', 'Li
ckitung', 'Chansey', 'Kangaskhan', 'Mega Kangaskhan', 'Tauros', 'Ditto', 'E
evee', 'Porygon', 'Snorlax'], (1, 'Poison'): ['Ekans', 'Arbok', 'Nidoran♀',
'Nidorina', 'Nidoqueen', 'Nidoran♂', 'Nidorino', 'Nidoking', 'Zubat', 'Golb
at', 'Grimer', 'Muk', 'Koffing', 'Weezing'], (1, 'Psychic'): ['Abra', 'Kada
bra', 'Alakazam', 'Mega Alakazam', 'Drowzee', 'Hypno', 'Mr. Mime', 'Mewtw
o', 'Mega Mewtwo X', 'Mega Mewtwo Y', 'Mew'], (1, 'Rock'): ['Geodude', 'Gra
veler', 'Golem', 'Onix', 'Omanyte', 'Omastar', 'Kabuto', 'Kabutops', 'Aerod
actyl', 'Mega Aerodactyl'], (1, 'Water'): ['Squirtle', 'Wartortle', 'Blasto
ise', 'Mega Blastoise', 'Psyduck', 'Golduck', 'Poliwag', 'Poliwhirl', 'Poli
wrath', 'Tentacool', 'Tentacruel', 'Slowpoke', 'Slowbro', 'Mega Slowbro',
'Seel', 'Dewgong', 'Shellder', 'Cloyster', 'Krabby', 'Kingler', 'Horsea',
'Seadra', 'Goldeen', 'Seaking', 'Staryu', 'Starmie', 'Magikarp', 'Gyarado
s', 'Mega Gyarados', 'Lapras', 'Vaporeon'], (2, 'Bug'): ['Ledyba', 'Ledia
n', 'Spinarak', 'Ariados', 'Yanma', 'Pineco', 'Forretress', 'Scizor', 'Mega
Scizor', 'Shuckle', 'Heracross', 'Mega Heracross'], (2, 'Dark'): ['Umbreo
n', 'Murkrow', 'Sneasel', 'Houndour', 'Houndoom', 'Mega Houndoom'], (2, 'El
ectric'): ['Pichu', 'Mareep', 'Flaaffy', 'Ampharos', 'Mega Ampharos', 'Elek
id', 'Raikou'], (2, 'Fairy'): ['Cleffa', 'Togepi', 'Togetic', 'Snubbull',
'Granbull'], (2, 'Fighting'): ['Tyrogue', 'Hitmontop'], (2, 'Fire'): ['Cynd
aquil', 'Quilava', 'Typhlosion', 'Slugma', 'Magcargo', 'Magby', 'Entei', 'H
o-oh'], (2, 'Ghost'): ['Misdreavus'], (2, 'Grass'): ['Chikorita', 'Baylee
f', 'Meganium', 'Bellossom', 'Hoppip', 'Skiploom', 'Jumpluff', 'Sunkern',
'Sunflora'], (2, 'Ground'): ['Gligar', 'Phanpy', 'Donphan'], (2, 'Ice'):
['Swinub', 'Piloswine', 'Delibird', 'Smoochum'], (2, 'Normal'): ['Sentret',
'Furret', 'Hoothoot', 'Noctowl', 'Igglybuff', 'Aipom', 'Girafarig', 'Dunspa
rce', 'Teddiursa', 'Ursaring', 'Porygon2', 'Stantler', 'Smeargle', 'Miltan
k', 'Blissey'], (2, 'Poison'): ['Crobat'], (2, 'Psychic'): ['Natu', 'Xatu',
'Espeon', 'Unown', 'Wobbuffet', 'Lugia', 'Celebi'], (2, 'Rock'): ['Sudowood
o', 'Larvitar', 'Pupitar', 'Tyranitar', 'Mega Tyranitar'], (2, 'Steel'):
['Steelix', 'Mega Steelix', 'Skarmory'], (2, 'Water'): ['Totodile', 'Crocon
aw', 'Feraligatr', 'Chinchou', 'Lanturn', 'Marill', 'Azumarill', 'Politoe
d', 'Wooper', 'Quagsire', 'Slowking', 'Qwilfish', 'Corsola', 'Remoraid', 'O
ctillery', 'Mantine', 'Kingdra', 'Suicune'], (3, 'Bug'): ['Wurmple', 'Silco
on', 'Beautifly', 'Cascoon', 'Dustox', 'Surskit', 'Masquerain', 'Nincada',
'Ninjask', 'Shedinja', 'Volbeat', 'Illumise'], (3, 'Dark'): ['Poochyena',
'Mightyena', 'Sableye', 'Mega Sableye', 'Absol', 'Mega Absol'], (3, 'Drago
n'): ['Altaria', 'Mega Altaria', 'Bagon', 'Shelgon', 'Salamence', 'Mega Sal
amence', 'Latias', 'Mega Latias', 'Latios', 'Mega Latios', 'Rayquaza', 'Meg
a Rayquaza'], (3, 'Electric'): ['Electrike', 'Manectric', 'Mega Manectric',
'Plusle', 'Minun'], (3, 'Fighting'): ['Makuhita', 'Hariyama', 'Meditite',
'Medicham', 'Mega Medicham'], (3, 'Fire'): ['Torchic', 'Combusken', 'Blazik
en', 'Mega Blaziken', 'Numel', 'Camerupt', 'Mega Camerupt', 'Torkoal'], (3,
'Ghost'): ['Shuppet', 'Banette', 'Mega Banette', 'Duskull', 'Dusclops'],
(3, 'Grass'): ['Treecko', 'Grovyle', 'Sceptile', 'Mega Sceptile', 'Seedot',
'Nuzleaf', 'Shiftry', 'Shroomish', 'Breloom', 'Roselia', 'Cacnea', 'Cacturn
e', 'Tropius'], (3, 'Ground'): ['Trapinch', 'Vibrava', 'Flygon', 'Baltoy',
'Claydol', 'Groudon', 'Primal Groudon'], (3, 'Ice'): ['Snorunt', 'Glalie',
'Mega Glalie', 'Spheal', 'Sealeo', 'Walrein', 'Regice'], (3, 'Normal'): ['Z
igzagoon', 'Linoone', 'Taillow', 'Swellow', 'Slakoth', 'Vigoroth', 'Slakin
g', 'Whismur', 'Loudred', 'Exploud', 'Azurill', 'Skitty', 'Delcatty', 'Spin
da', 'Swablu', 'Zangoose', 'Castform', 'Kecleon'], (3, 'Poison'): ['Gulpi
n', 'Swalot', 'Seviper'], (3, 'Psychic'): ['Ralts', 'Kirlia', 'Gardevoir',
'Mega Gardevoir', 'Spoink', 'Grumpig', 'Chimecho', 'Wynaut', 'Deoxys Normal
Forme', 'DeoxysAttack Forme', 'Deoxys Defense Forme', 'Deoxys Speed Form
e'], (3, 'Rock'): ['Nosepass', 'Lunatone', 'Solrock', 'Lileep', 'Cradily',
'Anorith', 'Armaldo', 'Regirock'], (3, 'Steel'): ['Mawile', 'Mega Mawile',
'Aron', 'Lairon', 'Aggron', 'Mega Aggron', 'Beldum', 'Metang', 'Metagross',
'Mega Metagross', 'Registeel', 'Jirachi'], (3, 'Water'): ['Mudkip', 'Marsht
omp', 'Swampert', 'Mega Swampert', 'Lotad', 'Lombre', 'Ludicolo', 'Wingul
l', 'Pelipper', 'Carvanha', 'Sharpedo', 'Mega Sharpedo', 'Wailmer', 'Wailor
d', 'Barboach', 'Whiscash', 'Corphish', 'Crawdaunt', 'Feebas', 'Milotic',
'Clamperl', 'Huntail', 'Gorebyss', 'Relicanth', 'Luvdisc', 'Kyogre', 'Prima
l Kyogre'], (4, 'Bug'): ['Kricketot', 'Kricketune', 'Burmy', 'Wormadam Plan
t Cloak', 'Wormadam Sandy Cloak', 'Wormadam Trash Cloak', 'Mothim', 'Combe
e', 'Vespiquen', 'Yanmega'], (4, 'Dark'): ['Honchkrow', 'Weavile', 'Darkra
i'], (4, 'Dragon'): ['Gible', 'Gabite', 'Garchomp', 'Mega Garchomp'], (4,
'Electric'): ['Shinx', 'Luxio', 'Luxray', 'Pachirisu', 'Magnezone', 'Electi
vire', 'Rotom', 'Heat Rotom', 'Wash Rotom', 'Frost Rotom', 'Fan Rotom', 'Mo
w Rotom'], (4, 'Fairy'): ['Togekiss'], (4, 'Fighting'): ['Riolu', 'Lucari
o', 'Mega Lucario'], (4, 'Fire'): ['Chimchar', 'Monferno', 'Infernape', 'Ma
gmortar', 'Heatran'], (4, 'Ghost'): ['Drifloon', 'Drifblim', 'Mismagius',
'Spiritomb', 'Dusknoir', 'Giratina Altered Forme', 'Giratina Origin Form
e'], (4, 'Grass'): ['Turtwig', 'Grotle', 'Torterra', 'Budew', 'Roserade',
'Cherubi', 'Cherrim', 'Carnivine', 'Snover', 'Abomasnow', 'Mega Abomasnow',
'Tangrowth', 'Leafeon', 'Shaymin Land Forme', 'Shaymin Sky Forme'], (4, 'Gr
ound'): ['Hippopotas', 'Hippowdon', 'Rhyperior', 'Gliscor'], (4, 'Ice'):
['Glaceon', 'Mamoswine', 'Froslass'], (4, 'Normal'): ['Starly', 'Staravia',
'Staraptor', 'Bidoof', 'Bibarel', 'Ambipom', 'Buneary', 'Lopunny', 'Mega Lo
punny', 'Glameow', 'Purugly', 'Happiny', 'Chatot', 'Munchlax', 'Lickilick
y', 'Porygon-Z', 'Regigigas', 'Arceus'], (4, 'Poison'): ['Stunky', 'Skuntan
k', 'Skorupi', 'Drapion', 'Croagunk', 'Toxicroak'], (4, 'Psychic'): ['Ching
ling', 'Mime Jr.', 'Gallade', 'Mega Gallade', 'Uxie', 'Mesprit', 'Azelf',
'Cresselia'], (4, 'Rock'): ['Cranidos', 'Rampardos', 'Shieldon', 'Bastiodo
n', 'Bonsly', 'Probopass'], (4, 'Steel'): ['Bronzor', 'Bronzong', 'Dialg
a'], (4, 'Water'): ['Piplup', 'Prinplup', 'Empoleon', 'Buizel', 'Floatzel',
'Shellos', 'Gastrodon', 'Finneon', 'Lumineon', 'Mantyke', 'Palkia', 'Phion
e', 'Manaphy'], (5, 'Bug'): ['Sewaddle', 'Swadloon', 'Leavanny', 'Veniped
e', 'Whirlipede', 'Scolipede', 'Dwebble', 'Crustle', 'Karrablast', 'Escaval
ier', 'Joltik', 'Galvantula', 'Shelmet', 'Accelgor', 'Durant', 'Larvesta',
'Volcarona', 'Genesect'], (5, 'Dark'): ['Purrloin', 'Liepard', 'Scraggy',
'Scrafty', 'Zorua', 'Zoroark', 'Pawniard', 'Bisharp', 'Vullaby', 'Mandibuz
z', 'Deino', 'Zweilous', 'Hydreigon'], (5, 'Dragon'): ['Axew', 'Fraxure',
'Haxorus', 'Druddigon', 'Reshiram', 'Zekrom', 'Kyurem', 'Kyurem Black Kyure
m', 'Kyurem White Kyurem'], (5, 'Electric'): ['Blitzle', 'Zebstrika', 'Emol
ga', 'Tynamo', 'Eelektrik', 'Eelektross', 'Thundurus Incarnate Forme', 'Thu
ndurus Therian Forme'], (5, 'Fighting'): ['Timburr', 'Gurdurr', 'Conkeldur
r', 'Throh', 'Sawk', 'Mienfoo', 'Mienshao'], (5, 'Fire'): ['Tepig', 'Pignit
e', 'Emboar', 'Pansear', 'Simisear', 'Darumaka', 'Darmanitan Standard Mod
e', 'Darmanitan Zen Mode', 'Heatmor'], (5, 'Flying'): ['Tornadus Incarnate
Forme', 'Tornadus Therian Forme'], (5, 'Ghost'): ['Yamask', 'Cofagrigus',
'Litwick', 'Lampent', 'Chandelure'], (5, 'Grass'): ['Snivy', 'Servine', 'Se
rperior', 'Pansage', 'Simisage', 'Cottonee', 'Whimsicott', 'Petilil', 'Lill
igant', 'Maractus', 'Foongus', 'Amoonguss', 'Ferroseed', 'Ferrothorn', 'Vir
izion'], (5, 'Ground'): ['Drilbur', 'Excadrill', 'Sandile', 'Krokorok', 'Kr
ookodile', 'Stunfisk', 'Golett', 'Golurk', 'Landorus Incarnate Forme', 'Lan
dorus Therian Forme'], (5, 'Ice'): ['Vanillite', 'Vanillish', 'Vanilluxe',
'Cubchoo', 'Beartic', 'Cryogonal'], (5, 'Normal'): ['Patrat', 'Watchog', 'L
illipup', 'Herdier', 'Stoutland', 'Pidove', 'Tranquill', 'Unfezant', 'Audin
o', 'Mega Audino', 'Minccino', 'Cinccino', 'Deerling', 'Sawsbuck', 'Bouffal
ant', 'Rufflet', 'Braviary', 'Meloetta Aria Forme', 'Meloetta Pirouette For
me'], (5, 'Poison'): ['Trubbish', 'Garbodor'], (5, 'Psychic'): ['Victini',
'Munna', 'Musharna', 'Woobat', 'Swoobat', 'Sigilyph', 'Gothita', 'Gothorit
a', 'Gothitelle', 'Solosis', 'Duosion', 'Reuniclus', 'Elgyem', 'Beheeyem'],
(5, 'Rock'): ['Roggenrola', 'Boldore', 'Gigalith', 'Archen', 'Archeops', 'T
errakion'], (5, 'Steel'): ['Klink', 'Klang', 'Klinklang', 'Cobalion'], (5,
'Water'): ['Oshawott', 'Dewott', 'Samurott', 'Panpour', 'Simipour', 'Tympol
e', 'Palpitoad', 'Seismitoad', 'Basculin', 'Tirtouga', 'Carracosta', 'Duckl
ett', 'Swanna', 'Frillish', 'Jellicent', 'Alomomola', 'Keldeo Ordinary Form
e', 'Keldeo Resolute Forme'], (6, 'Bug'): ['Scatterbug', 'Spewpa', 'Vivillo
n'], (6, 'Dark'): ['Inkay', 'Malamar', 'Yveltal'], (6, 'Dragon'): ['Goomy',
'Sliggoo', 'Goodra', 'Zygarde Half Forme'], (6, 'Electric'): ['Helioptile',
'Heliolisk', 'Dedenne'], (6, 'Fairy'): ['Flabébé', 'Floette', 'Florges', 'S
pritzee', 'Aromatisse', 'Swirlix', 'Slurpuff', 'Sylveon', 'Xerneas'], (6,
'Fighting'): ['Pancham', 'Pangoro', 'Hawlucha'], (6, 'Fire'): ['Fennekin',
'Braixen', 'Delphox', 'Fletchinder', 'Talonflame', 'Litleo', 'Pyroar', 'Vol
canion'], (6, 'Flying'): ['Noibat', 'Noivern'], (6, 'Ghost'): ['Phantump',
'Trevenant', 'Pumpkaboo Average Size', 'Pumpkaboo Small Size', 'Pumpkaboo L
arge Size', 'Pumpkaboo Super Size', 'Gourgeist Average Size', 'Gourgeist Sm
all Size', 'Gourgeist Large Size', 'Gourgeist Super Size'], (6, 'Grass'):
['Chespin', 'Quilladin', 'Chesnaught', 'Skiddo', 'Gogoat'], (6, 'Ice'): ['B
ergmite', 'Avalugg'], (6, 'Normal'): ['Bunnelby', 'Diggersby', 'Fletchlin
g', 'Furfrou'], (6, 'Poison'): ['Skrelp', 'Dragalge'], (6, 'Psychic'): ['Es
purr', 'Meowstic Male', 'Meowstic Female', 'Hoopa Confined', 'Hoopa Unboun
d'], (6, 'Rock'): ['Binacle', 'Barbaracle', 'Tyrunt', 'Tyrantrum', 'Amaur
a', 'Aurorus', 'Carbink', 'Diancie', 'Mega Diancie'], (6, 'Steel'): ['Honed
ge', 'Doublade', 'Aegislash Blade Forme', 'Aegislash Shield Forme', 'Klefk
i'], (6, 'Water'): ['Froakie', 'Frogadier', 'Greninja', 'Clauncher', 'Clawi
tzer']}

Q. Group by Generation and get the


mean value of attack for each
generation
In [24]: df.groupby('Generation')['Attack'].mean() #aggregate function
Out[24]: Generation
1 76.638554
2 72.028302
3 81.625000
4 82.867769
5 82.066667
6 75.804878
Name: Attack, dtype: float64

In [25]: df.groupby('Generation')['Sp. Atk'].median()

Out[25]: Generation
1 65.0
2 65.0
3 70.0
4 71.0
5 65.0
6 65.0
Name: Sp. Atk, dtype: float64

In [26]: df.groupby('Generation')['Attack'].mean().sort_values(ascending=True)

Out[26]: Generation
2 72.028302
6 75.804878
1 76.638554
3 81.625000
5 82.066667
4 82.867769
Name: Attack, dtype: float64

Q. Find the fastest pokemon in type 1


In [27]: df.groupby('Type 1')['Speed'].max().sort_values(ascending=False).idxmax()

Out[27]: 'Psychic'

Pivot table
In [28]: pd.pivot_table(df,index='Generation',values='Sp. Atk',aggfunc='sum')
Out[28]: Sp. Atk

Generation

1 11922

2 6990

3 12129

4 9245

5 11878

6 6092

In [29]: df.groupby('Type 1')['Speed'].max().sort_values(ascending=False).idxmax()

Out[29]: 'Psychic'

In [30]: df['Attack'].unique()

Out[30]: array([ 49, 62, 82, 100, 52, 64, 84, 130, 104, 48, 63, 83, 103,
30, 20, 45, 35, 25, 90, 150, 60, 80, 56, 81, 85, 55,
75, 47, 92, 57, 72, 102, 70, 41, 76, 50, 65, 95, 105,
110, 40, 120, 73, 5, 125, 67, 155, 10, 115, 135, 134, 190,
46, 38, 58, 33, 185, 164, 160, 51, 71, 91, 140, 43, 78,
15, 165, 68, 23, 145, 180, 89, 109, 66, 86, 42, 29, 59,
79, 69, 94, 136, 93, 24, 170, 112, 61, 106, 132, 123, 88,
53, 98, 77, 27, 117, 108, 44, 87, 147, 74, 124, 97, 129,
128, 107, 36, 22, 54, 121, 131], dtype=int64)

In [31]: def chk_attack(x):


if x<60:
return "Low attack"
elif x>60 and x<120:
return "Normal attack"
else:
return "High attack"
df['Attack']=df['Attack'].apply(chk_attack)
df
Out[31]: Type Health Sp. Sp.
Type 1 Attack Defense Speed Gener
2 Points Atk Def

Name

Low
Bulbasaur Grass Poison 45 49 65 65 45
attack

Normal
Ivysaur Grass Poison 60 63 80 80 60
attack

Normal
Venusaur Grass Poison 80 83 100 100 80
attack

Mega Normal
Grass Poison 80 123 122 120 80
Venusaur attack

Low
Charmander Fire NaN 39 43 60 50 65
attack

... ... ... ... ... ... ... ... ...

Normal
Diancie Rock Fairy 50 150 100 150 50
attack

Mega High
Rock Fairy 50 110 160 110 110
Diancie attack

Hoopa Normal
Psychic Ghost 80 60 150 130 70
Confined attack

Hoopa High
Psychic Dark 80 60 170 130 80
Unbound attack

Normal
Volcanion Fire Water 80 120 130 90 70
attack

800 rows × 11 columns

Merging()
In [32]: df1 = pd.DataFrame({'fruit': ['apple', 'banana', 'orange'],
'weight': ['high', 'medium', 'low'],
'price': np.random.randint(0, 15, 3)})

df2 = pd.DataFrame({'fruit': ['apple', 'orange', 'pine'],


'kilo': ['high', 'medium', 'low'],
'price': np.random.randint(0, 15, 3)})

In [33]: df1
Out[33]: fruit weight price

0 apple high 5

1 banana medium 4

2 orange low 10

In [34]: df2

Out[34]: fruit kilo price

0 apple high 13

1 orange medium 5

2 pine low 12

In [35]: #inner
#outer
#left
#right

In [36]: pd.merge(left=df1,right=df2,on='fruit',how='inner') #on-which column, how-

Out[36]: fruit weight price_x kilo price_y

0 apple high 5 high 13

1 orange low 10 medium 5

In [37]: pd.merge(left=df1,right=df2,on='fruit',how='outer') # all the values

Out[37]: fruit weight price_x kilo price_y

0 apple high 5.0 high 13.0

1 banana medium 4.0 NaN NaN

2 orange low 10.0 medium 5.0

3 pine NaN NaN low 12.0

In [38]: pd.merge(left=df1,right=df2,on='fruit',how='left') #only the fruits in df1

Out[38]: fruit weight price_x kilo price_y

0 apple high 5 high 13.0

1 banana medium 4 NaN NaN

2 orange low 10 medium 5.0

In [39]: pd.merge(left=df1,right=df2,on='fruit',how='right') #only the fruits in df2


Out[39]: fruit weight price_x kilo price_y

0 apple high 5.0 high 13

1 orange low 10.0 medium 5

2 pine NaN NaN low 12

This notebook was converted with convert.ploomber.io

You might also like