jas_0n
jas_0n

Reputation: 93

Replace value in column by value in list by index

My column in dataframe contains indices of values in list. Like:

id | idx  
A  |  0  
B  |  0  
C  |  2  
D  |  1  

list  = ['a', 'b', 'c', 'd'] 

I want to replace each value in idx column greater than 0 by value in list of corresponding index, so that:

id | idx  
A  |  0  
B  |  0  
C  |  c     # list[2]
D  |  b     # list[1]

I tried to do this with loop, but it does nothing...Although if I move ['idx'] it will replace all values on this row

for index in df.idx.values:
    if index >=1:
        df[df.idx==index]['idx'] = list[index]

Upvotes: 2

Views: 742

Answers (2)

jezrael
jezrael

Reputation: 863531

Dont use list like variable name, because builtin (python code word).

Then use Series.map with enumerate in Series.mask:

L  = ['a', 'b', 'c', 'd'] 
df['idx'] = df['idx'].mask(df['idx'] >=1, df['idx'].map(dict(enumerate(L))))
print (df)
  id idx
0  A   0
1  B   0
2  C   c
3  D   b

Similar idea is processing only matched rows by mask:

L  = ['a', 'b', 'c', 'd'] 
m = df['idx'] >=1
df.loc[m,'idx'] = df.loc[m,'idx'].map(dict(enumerate(L)))
print (df)
  id idx
0  A   0
1  B   0
2  C   c
3  D   b

Upvotes: 3

sammywemmy
sammywemmy

Reputation: 28729

Create a dictionary for items where the index is greater than 0, then use the mapping with replace to get your output :

mapping = dict((key,val) for key,val in enumerate(l) if key > 0)

print(mapping)

{1: 'b', 2: 'c', 3: 'd'}


df.replace(mapping)


id  idx
0   A   0
1   B   0
2   C   c
3   D   b

Note : I changed the list variable name to l

Upvotes: 1

Related Questions