How can I create a new columns matching a column with lists in a dataframe with the indexes of another dataframe?

Viewed 27

I have a dataframe with a column that contains lists of items. The second dataframe contains the values associated with the items of the previous mentioned dataframe.

| df1                              |      | df2                     |   |             |

|          lists of items          |      |            item         |   | values      |
| ["items1","items4","items2500"]  |      |          "item1"        |   | 234         |
| ["items4","items56","items3450"] |      |          "item2 "       |   | 1325        |
| ["items3","items26","items1250"] |                    .
               .                                        .
               .                          |          "item3450"     |   | 2345        |
               .

What I would like to obtain is a new column in the dataframe 1 in which in each cell i would obtain the mean of the item values

For example

| ["items1","items4","items2500"]  |      |             "item1"        |   | 234                |
                                          |             "item4"        |   | 2                  |
                                          |             "item2500"     |   | 3                  |

The new column should have (234+2+3)/3 for the first row and do the same for each row of the df1

in the df2 item is set as the index but I don't know if it would be simpler use it as a column.

Is there any way to achieve the above result?

1 Answers

I don't know if I got it right, but maybe this could help:

You can do math between columns in a dataframe. Try using this and check if that's what you need:

df = pd.DataFrame({'A':[1,2,3,4,5],'B':[2,3,4,5,6],'C':[0,1,2,3,4]})

df['mean'] = (df['A'] + df['B'] + df['C'])/3

print(df)

Related