0

I am trying to use loop through ind_num to match the index value using iloc .. then replace the value next to the index value by looping through designation.

this is an example problem which closely reflect a project I am working on .. but I feel this example makes it easier for others to understand what I'm trying to accomplish.

import pandas as pd

data = [['h', 'zero'], ['i', 'circle'], ['j', 'two'], ['k','square']] 
#goal is to replace 'circle' and 'square' with 'one' and 'three' respectively 


df = pd.DataFrame(data, columns=['letters', 'ind_name'])

print(df)

ind_num = [1, 3]

designation = ['one', 'three']


'''for x in ind_num
    for y in designation
        df.iloc[x][1]''' # not sure where to go from here
dane w
  • 1
  • 3
  • Does this answer your question? [Replace values in a pandas column based on dictionary/mapping of indices](https://stackoverflow.com/questions/54054604/replace-values-in-a-pandas-column-based-on-dictionary-mapping-of-indices) – Ignatius Reilly Aug 31 '22 at 15:53
  • For the solution in the suggested duplicate, you can create a dic for replacements with `designation_dic = {ind_num[i]:designation[i] for i in range(len(ind_num))}` – Ignatius Reilly Aug 31 '22 at 15:57
  • But if really want to loop, taking into account that both `ind_number` and `designation` should have the same length: `for i in range(len(ind_num)): df.iloc[ind_num[i]][1] = designation[i]` – Ignatius Reilly Aug 31 '22 at 16:01
  • thank you for the help. I'm sure the answer is in here somewhere .. but my knowledge is not sophisticated enough to understand it ha – dane w Aug 31 '22 at 19:18
  • Try looking at [Pandas Dataframe, using iloc to replace last row](https://stackoverflow.com/a/51645414/16653700). – Alias Cartellano Aug 31 '22 at 19:28

1 Answers1

0

If you iterate over each element of ind_num and then designation, you are going to end up iterating over all combinations (1 - 'one', 1 - 'three', 2 - 'one', 2 - 'three').

Because ind_num and designation should have the same length, you can simply do

for i in range(len(ind_num)):
    df.iloc[ind_num[i]][1] = designation[i]

Or, you can just generate a dictionary mapping index to updated value and use pandas' update:

designation_dic = {ind_num[i]:designation[i] for i in range(len(ind_num))}

df['ind_name'].update(pd.Series(designation_dic))

The first line just uses dictionary comprehension to produce {1: 'one', 3: 'three'}

Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15