在 pandas 中应用函数

当我运行以下命令时


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]) 

我收到以下错误


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

我 100% 确信这在过去是有效的,因为我已经广泛使用了它。有谁知道为什么会发生这种情况?


慕后森
浏览 101回答 1
1回答

慕虎7371278

最后把最后一张地图扔掉就可以了。该函数正在返回一个列表,而您的最后一个映射函数正在尝试获取列表的第一个元素。import pandas as pddef my_func(E, I):&nbsp; &nbsp; return E * Id = {'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)或者,但根据此处的注释,您可以将 my_func 的值作为列表返回:import pandas as pddef my_func(E, I):&nbsp; &nbsp; 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])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python