“Series”对象不能在具有列表的数据帧列上调用

2024-09-30 01:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多行和列的数据框架。 其中一列-“诊断超类”将每个患者的标签存储在列表行中。 看起来是这样的:

['MI', 'HYP', 'STTC']
['MI', 'CD', 'STTC']

我需要从每行获取第一个标签所需输出是一列,存储每行的第一个列表元素 所以我写了一个函数:

def labels(column_with_lists):
    label = column_with_lists
    for a in column_with_lists() :
        list_label = column_with_lists[0]
        label = list_label[0]
    return label

因此,当我运行代码时,我面临以下问题:

Traceback (most recent call last):
  File "C:/Users/nikit/PycharmProjects/ECG/ECG.py", line 77, in <module>
    print(labels(y_true['diagnostic_superclass']))
  File "C:/Users/nikit/PycharmProjects/ECG/ECG.py", line 63, in labels
    for a in column_with_lists() :
TypeError: 'Series' object is not callable

Tags: in列表forlabelswithcolumn标签users
2条回答

错误是因为变量名后面有(),这意味着将其作为函数调用。这是一个熊猫系列,不是一个功能

从列表系列中获取新系列的一种方法是使用pandas.Series.apply()

def labels(column_with_lists):
    return column_with_lists.apply(lambda x: x[0])

正如@Vivek Kalyanarangan所说,去掉括号,它就会起作用,但我认为你很困惑,如果你什么都不使用“a”,为什么要在这一部分迭代

for a in column_with_lists :
    list_label = column_with_lists[0]
    label = list_label[0]

我认为您必须在列表中存储每行的第一项。事实上,您不需要使用函数:

first_element_of_each_row = [i[0] for i in y_true['diagnostic_superclass'].to_numpy()]

这应该是工作

相关问题 更多 >

    热门问题