Home > Software design >  iterrows() producing empty column
iterrows() producing empty column

Time:03-20

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

CodePudding user response:

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

CodePudding user response:

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
  • Related