Add a series to existing DataFrame

Viewed 37977

I created the following DataFrame:

purchase_1 = pd.Series({'Name': 'Chris',
                        'Item Purchased': 'Dog Food',
                        'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
                        'Item Purchased': 'Kitty Litter',
                        'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
                        'Item Purchased': 'Bird Seed',
                        'Cost': 5.00})

df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])

I then added the following column:

df['Location'] = df.index
df

How do I then add the following series to the my DataFrame? Thank you.

s = pd.Series({'Name':'Kevyn', 'Item Purchased': 'Kitty Food', 'Cost': 3.00, 'Location': 'Store 2'})
3 Answers

I hope it will be helpful and give you the accurate result,

purchase_4 = pd.Series({'Name': 'Kevyn', 
                        'Item Purchased': 'Kitty Food', 
                        'Cost': 3.00,
                       'Location': 'Store 2'})
df2 = df.append(purchase_4, ignore_index=True)
df2.set_index(['Location', 'Name'])

Solution directly from the source of your question.

df = df.set_index([df.index, 'Name'])
df.index.names = ['Location', 'Name']
df = df.append(pd.Series(data={'Cost': 3.00, 'Item Purchased': 'Kitty Food'}, name=('Store 2', 'Kevyn')))
df
Related