Search code examples
pythondataframefilteringenumerate

how to use enumerate in a filtered dataframe


Community! thanks for all the support I'm receiving so far!

I have this following dataframe as an example:

d = {'country': ['argentina', 'argentina', 'colombia', 'australia', 'england', 'england', 'china', 'india', 'emirates', 'togo'], 'numbers': [39, 30, 20, 71, 44, 56, 21, 45, 29,33]}

df = pd.DataFrame(data=d)

enter image description here

Actually, the one I'm working with has 30,000 rows and I filtered it several times (around 10 times)

After all filters I got something like:

enter image description here

Indexes are different because of the filter.

Now I came to a point I have to replace the name of the country for 'egd' if it starts with 'e', so I came up with:

for i, row in enumerate(df['country']):

    if row.startswith('e'):

        df['country'][i] = 'egd'

and the warning is:

enter image description here

Actually, the following code didn´t work

I understand It's because of the different value from enumerate 'i' that the filtered dataframe has compared to the index of the original one.

What is the best way to approach this situation? Deleting filtered rows? Is there any way I can delete filtered rows? (in the example above: row 1, 2, 3, 6, 8)

Thanks in advance!!


Solution

  • More pandas way to do it is to use map

    df['country'] = df['country'].map(lambda s: 'egd' if s.startswith('e') else s)