Vic13
Vic13

Reputation: 561

Inserting dictionary values in pandas column

C is my column in pandas dataframe(df). And it consists of many lists.

          C
  [ab ab bc abb]
  [ll li lo ll]

D is my dictionary which is as follows.

D={'ab':0, 'bc':1, 'abb':2, 'll':3, 'li':4, 'lo':5}

Now, I want to assign the values of my dictionary to the list and for that, I am using the below mentioned code.

df.C= [D[item] for item in df.C]

Here, I am getting this error:

TypeError: list indices must be integers or slices, not str.

Thanks for the help.

Upvotes: 1

Views: 75

Answers (1)

cs95
cs95

Reputation: 402333

Looks like you have a list of space separated strings, so you'll need two loops, not one. Try this instead:

df.C = [[D[j] for j in i.split()] for i df.C]

If you have to handle missing keys, use dict.get instead:

df.C = [[D.get(j, -1) for j in i.split()] for i df.C]

Where -1 is some default value.

Upvotes: 2

Related Questions