2

I am iterating through a dataframe and pulling out specific lines and then enriching those lines with some other elements. I have a dictionary that has the following definition mapping:

testdir = {0: 'zero', 40: 'forty', 60: 'sixty', 80: 'eighty'}

When i pull out a specific line from the original dataframe which looks like this

a   b   c      x   str
0  0   0   0  100.0  aaaa

i want the str cell to now be set to the string value of column c which is 0 so

output should be

a   b   c      x   str
0  0   0   0  100.0  zero

and then after meeting some other conditions a new line is pulled out from the original dataframe and the output should be

a   b   c      x   str
0  0   0   0  100.0  zero
3  4  30  60  100.0  sixty

i tried to use the map() method so something like'

df['str'][-1] = df['c'][-1].map(testdir)

but i'm erroring all over the place!

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
pv80
  • 21
  • 1
  • 1
    Does this answer your question? [Adding a new pandas column with mapped value from a dictionary](https://stackoverflow.com/questions/24216425/adding-a-new-pandas-column-with-mapped-value-from-a-dictionary) – David Erickson Jun 15 '20 at 07:53

1 Answers1

1

map is intended for pd.Series, so if you can, just map the entire column when it is fully populated, that way you avoid the oevrhead of multiple calls to map:

df['str'] = df.c.map(testdir)

print(df)

   a   b   c      x    str
0  0   0   0  100.0   zero
3  4  30  60  100.0  sixty

Note that, to correctly index the dataframe on a single cell, and map with the dictionary, you need something like:

testdir[df.iat[-1, 2]]

Chained indexing as df['c'][-1] is discouraged in the docs, and has a negative effect when assigning, which is that your not updating the original dataframe, since it returns a copy.

yatu
  • 86,083
  • 12
  • 84
  • 139