James Soh James Soh - 2 years ago 148
Python Question

How to replace column data (which are Indexes of a series) with corresponding Values of a series

prices #This is a Pandas series
Apple 3
Banana 2
Pear 5

df.sales
Apple
Pear
Pear
Banana


I want to map the prices in the Series over to df.sales, so that df.sales becomes

3
5
5
2

Answer Source

It seems you need map or replace:

#all non match values are replace to NaN
df['sales'] = df['sales'].map(s)

Or:

#all non match values are not changed
df['sales'] = df['sales'].replace(s)

#index values have to be unique
s = pd.Series([3,2,5],index=['Apple','Banana','Pear'])
df = pd.DataFrame({'sales':['Apple','Pear','Pear','Banana', 'Orange']})

df['sales1'] = df['sales'].map(s)
df['sales2'] = df['sales'].replace(s)
print (df)
    sales  sales1  sales2
0   Apple     3.0       3
1    Pear     5.0       5
2    Pear     5.0       5
3  Banana     2.0       2
4  Orange     NaN  Orange
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download