How to insert the values of different columns of the same length compared to two different DFs of Pandas

Asked 2 years ago, Updated 2 years ago, 145 views

For example, the data below and

gnr_name    gnrOneHot
It's a ballad
1 pop 1
2 80 2

Compare the data below,

0 [Ballad]
1. [Pop, Recalling]
2. [Cafe, calm]

I'd like to change it as below.

Is there any way you can do it at once?

0 [0]
1 [1, 23]
2 [45, 56]

python pandas nlp

2022-09-21 10:14

1 Answers

I think there's a simpler way, a little more ignorant

>>> import pandas as pd
>> df = pd.DataFrame ({"name":["foot", "pop", "arm"], "onehot":[0,1,2]})
>>> df
  name  onehot
Zero, zero
One pop one
Two arms two

>>> name_idx_map = { r['name']:r['onehot'] for _, r in df.iterrows() }
>>> name_idx_map
{'foot': 0, 'pop': 1, 'arm': 2'
>>> data = pd.Series (['Foot'], ['Pop', 'Arm'
>>> data
0 [Foot]
1. [Pop, arm]
dtype: object
>>> data.apply(lambda e: [ name_idx_map[k] for k in e ])
0       [0]
1    [1, 2]
dtype: object
>>> 


2022-09-21 10:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.