user4218673
user4218673

Reputation: 59

Replace pandas values as index to another array

Consider an array

a = np.array([5, 12, 56, 36])

and a pandas dataframe

b = pandas.DataFrame(np.array([1, 3, 0, 3, 1, 0, 2]) 

how does one replace the values on b by using its values as indexes for a, i.e., the intended value is:

c = pandas.DataFrame([12, 36, 5, 36, 12, 5, 56])

Can't quite figure this out.

Upvotes: 1

Views: 921

Answers (3)

BENY
BENY

Reputation: 323316

Let us try something different Series.get

pd.Series(a).get(b[0])
Out[57]: 
1    12
3    36
0     5
3    36
1    12
0     5
2    56
dtype: int32

Upvotes: 1

Vaishali
Vaishali

Reputation: 38415

One way is using apply,

c = b.apply(lambda x: a[x])

Or by indexing the numpy array and passing the values to DataFrame,

c = pd.DataFrame(a[b[0].values])


    0
0   12
1   36
2   5
3   36
4   12
5   5
6   56

Upvotes: 2

hakan.t
hakan.t

Reputation: 95

map can be used.

b.a.map({i:j for i,j in enumerate(a)})
0    12
1    36
2     5
3    36
4    12
5     5
6    56
Name: a, dtype: int64

Upvotes: 0

Related Questions