0

I'm not attached to using a dictionary for a lookup table, if there's a better way to go. I've created a simple Python dictionary (lkup) to use as a lookup table with input from df.letter. I'd like to output the mapped values from the dictionary into a new column, df.newletter. The snippet below works up until the actual assignment in the final line.

I've tried using only numeric indexes, using keys, values, dict.get(), and a number of other things. Am I close?

import pandas as pd

df = pd.DataFrame()
df['letter'] = ['a', 'a', 'c', 'd', 'd']
lkup = {'a':'b', 'b':'c', 'c':'d', 'd':'e', 'e':'f'}

for key in lkup:
    for i in range(0,4):
        if df['letter'][i] in key:
            df['newletter'][i] = [insert_dictionary_value]

I'd like to see the mapped dictionary values in the df.newletter column.

4

1 回答 1

4

You don't need a loop to do that, just assign the new column to values of the old column mapped by the dictionary using df.map:

...
>>> df['newletter'] = df['letter'].map(lkup)
>>> print(df)
  letter newletter
0      a         b
1      a         b
2      c         d
3      d         e
4      d         e
于 2019-08-04T23:45:48.800 回答