Home > database >  rename all the values in a Pandas column using an iteration (a for loop)
rename all the values in a Pandas column using an iteration (a for loop)

Time:01-12

I have the need to rename all the values in a Pandas column (from a data frame) and I want the new values to have "iterated-like" new names.

Let's say my data frame (df) has a column named "animals" with some values like "dog, cat, pig, etc", which are all strings. I want to rename all the values and I want the new values to be like "animal_1, animal_2, animal_3, etc".

I've tried something like:

for i in range (1, 20):
   for val in df['animals']:
      df['animals'].replace({'val' : 'animal_(i)'})

but it does not work at all...

Any suggestions on how to do it?

CodePudding user response:

If there is default RangeIndex is possible use:

df['animals'] = 'animal_   ('df.index   1).astype(str)

Or use list comprehension with f-strings:

df['animals'] = [f'animal_{i   1}' for i in df.index]

For any index:

df['animals'] = [f'animal_{i   1}' for i in np.arange(len(df.index))]

CodePudding user response:

many thanks. I've tried the third one, because I've liked the most:

df['animals'] = [f'animal_{i   1}' for i in np.arange(len(df.index))]

and it works well. But....I've made a mistake, in the definition of the problem. Using this method any value becomes "animal_(i)", where 'i' goes from 1 to the number of rows (and, in fact, it is "linked" to RangeIndex).

This means that, i.e., if I have 32 values which are "dog"...any "dog" value becomes "animal_1, animal_32, animal_56, ecc", depending on the index position, related to the row...

what if I want that every "dog" value becomes the same "animal_x" (where i=x, and I'm not interested in the specific "x" value that 'i' has become)?

This is why I've tried to use a for loop, with no good solution...

  •  Tags:  
  • Related