Giorgos Synetos
Giorgos Synetos

Reputation: 467

apply function in pandas

When i run the following

import pandas as pd


def my_func(E, I):

    return E * I


d = {'E': [1, 1], 'I': [2, 2]}
df = pd.DataFrame(data=d)
df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1).map(lambda x: x[0]) 

I get the following error

Traceback (most recent call last):
  File "U:\GSY\scipt.py", line 14, in <module>
    df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1).map(lambda x: x[0])
  File "C:\Users\gsy.LSH\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\series.py", line 3630, in map
    new_values = super()._map_values(arg, na_action=na_action)
  File "C:\Users\gsy.LSH\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\pandas\core\base.py", line 1145, in _map_values
    new_values = map_f(values, mapper)
  File "pandas\_libs\lib.pyx", line 2329, in pandas._libs.lib.map_infer
  File "U:\GSY\script.py", line 14, in <lambda>
    df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1).map(lambda x: x[0])
TypeError: 'int' object is not subscriptable

I 'm 100% sure that this was working in the past as i have used it extensively. Does anyone know why this is happening?

Upvotes: 0

Views: 87

Answers (1)

B. Bogart
B. Bogart

Reputation: 1075

Just drop the last map at the end. The function is returning a list and your last map function is trying to take the first element of a list.

import pandas as pd

def my_func(E, I):
    return E * I

d = {'E': [1, 1], 'I': [2, 2]}
df = pd.DataFrame(data=d)
df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1)

Alternatively but based on the comments here you could return the value from my_func as a list:

import pandas as pd

def my_func(E, I):
    return [E * I]

d = {'E': [1, 1], 'I': [2, 2]}
df = pd.DataFrame(data=d)
df['S'] = df.apply(lambda x: my_func(x['E'], x['I']),axis=1).map(lambda x: x[0])

Upvotes: 1

Related Questions