0

I am trying to use iterrows() in a for loop to add data to a new column within a dataframe. However, this sadly produces just a new empty column. I am not entirely sure where I am going wrong here. When you run the code, print(row['Key_words']) output values, so its not like there isn't any data in the new column because there is nothing to add.

I am not sure what's going wrong here. The frustrating part is this has worked just fine for me in the past. I am wondering if there are any revisions to the code/alternative solutions to solve this problem?

Data:

df = pd.DataFrame({'id': {0: 1, 1: 2, 2: 3}, 'name': {0: 'Sandwich Cookies', 1: 'All-Seasons Salt', 2: 'Unsweetened Oolong Tea'}, 'a_id': {0: 'cookies cakes', 1: 'spices seasonings', 2: 'tea'}, 'd_id': {0: 'snacks', 1: 'pantry', 2: 'beverages'}})

Example code:

df['Key_words'] = ''
i = 1
for index, row in df.iterrows():
    row['Key_words'] = list(str(i))
    i = i + 1
    print(row['Key_words'])

df
3
  • 1
    Iterating over a pandas df is generally speaking not a good idea (performance-wise). What do you want to accomplish? Commented Mar 20, 2022 at 13:29
  • @DocZerø I'm really just trying to add new data to the new column Key_words Commented Mar 20, 2022 at 13:34
  • The empty column is created by the first line. If you want to add data to the row in this way you should do df.loc[index, 'Key_words'] = list(str(i)), however, as DocZero mentioned, this is very slow. Beter to first create a list of the data and add that to the data frame in one go Commented Mar 20, 2022 at 13:36

2 Answers 2

2

Try this:

df['Key_words'] = ''
i = 1
for index, row in df.iterrows():
    df.loc[index, 'Key_words'] = list(str(i))
    i = i + 1
    print(row['Key_words'])

df
Sign up to request clarification or add additional context in comments.

Comments

1

This should solve the issue without having to resort to iterating row by row. This assumes that your index is as shown in your post (thus starting from 0).

df['key_words'] = df.apply(lambda x: x.name+1, axis=1)
id name a_id d_id key_words
0 1 Sandwich Cookies cookies cakes snacks 1
1 2 All-Seasons Salt spices seasonings pantry 2
2 3 Unsweetened Oolong Tea tea beverages 3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.