import sys import pandas as pd data = { "New York": "The Empire State", "New Jersey": "The Garden State", "Connecticut": "The Constitution State" } series = pd.Series(data = data, name = "nicknames") series.index.name = "name" print(series) print() print(f"{series.index = }") print() #Keep the same rows, but in a different order. index = pd.Index(data = sorted(data.keys()), name = "name") #Create a new index. series = series.reindex(index = index) print(series) print() print(f"{series.index = }") sys.exit(0)
name New York The Empire State New Jersey The Garden State Connecticut The Constitution State Name: nicknames, dtype: object series.index = Index(['New York', 'New Jersey', 'Connecticut'], dtype='object', name='name') name Connecticut The Constitution State New Jersey The Garden State New York The Empire State Name: nicknames, dtype: object series.index = Index(['Connecticut', 'New Jersey', 'New York'], dtype='object', name='name')
import sys import pandas as pd data = { "New York": "The Empire State", "New Jersey": "The Garden State", "Connecticut": "The Constitution State" } series = pd.Series(data = data, name = "nicknames") series.index.name = "name" print(series) print() print(f"{series.index = }") print() #Delete "Connecticut", insert "New Mexico". index = pd.Index(data = ["New York", "New Mexico", "New Jersey"], name = "name") #Create a new index. series = series.reindex(index = index, fill_value = "The Unknown State") print(series) print() print(f"{series.index = }") sys.exit(0)
name New York The Empire State New Jersey The Garden State Connecticut The Constitution State Name: nicknames, dtype: object series.index = Index(['New York', 'New Jersey', 'Connecticut'], dtype='object', name='name') name New York The Empire State New Mexico The Unknown State New Jersey The Garden State Name: nicknames, dtype: object series.index = Index(['New York', 'New Mexico', 'New Jersey'], dtype='object', name='name')
What do you get if you don’t specify a
fill_value
?