1

When I try to read each element in a column of Dataframe, I cannot use replace to change a old substring into a new substring, the text will have the same value after using replace.

for index, row in df.iterrows():
    text = row['r.name']
    print(type(text))
    for token in row['main_ingreds'].split(','):
        text.replace(token, " ")
ltbinh
  • 39
  • 1
  • 6
  • 2
    Please provide sample input and expected output: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples . A better solution than iterating through rows here will be list comprehension... for example a one-liner `df['main_ingreds'] = df['main_ingreds'].apply(lambda x: [list generation replace logic])` – David Erickson Jul 15 '20 at 07:29
  • ``` import pandas as pd df = pd.DataFrame({'r.name': ['ABCD', 'DEFG', 'OMNP'], 'main_ingreds': [A, FG, NP]}) ``` Output should be df['r.name'] = ['BCD','DE','OM'] – ltbinh Jul 15 '20 at 08:03
  • always put code, data and error message in question, not in comment - it will be more readable and more people will see it. – furas Jul 15 '20 at 09:01

1 Answers1

0

You don't have to iterate but use apply(function, axis=1)

import pandas as pd

df = pd.DataFrame({
    'r.name': ['ABCD', 'DEFG', 'OMNP'],
    'main_ingreds': ['A', 'FG', 'NP']
})

def func(row):
    for token in row['main_ingreds'].split(','):
        row['r.name'] = row['r.name'].replace(token, " ")
    return row

df = df.apply(func, axis=1)

print( df['r.name'] )
furas
  • 134,197
  • 12
  • 106
  • 148