Search code examples
pythonpandas

How to add a number to each element in a list that is a row of a column of df?


I have a df, in which there is a column, namely "foo". In this column, each entry is a list of numbers. I can keep the first 4 numbers for each entry in this column by df["foo"] = df["foo"].apply(lambda row: row[0:4]). For example, the first entry is 0, 1, 2, 3, 4, 5, 6. Then, the resulting first entry would become 0, 1, 2, 3.

Now, I want to add a number (let's say 10) to each element in each entry. From here, one can add an integer to each element in a list by new_list = [x+1 for x in my_list]. This is what I want, using the same example: 10, 11, 12, 13, 14, 15, 16.

I would like to do something like df["foo"] = df["foo"].apply(lambda row: x+10 for x in row). But this naive approach does not work.

The error is NameError: name 'row' is not defined


Solution

  • Simply use the lambda function like this:

    df["foo"] = df["foo"].apply(lambda row: [x + 10 for x in row])