如何使用系列的相应值替换列数据(系列的索引)

时间:2017-10-02 05:50:08

标签: python pandas

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

df.sales
Apple
Pear
Pear
Banana

我想将系列中的价格映射到df.sales,以便df.sales变为

3
5
5
2

1 个答案:

答案 0 :(得分:2)

您似乎需要mapreplace

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

或者:

#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