如何将函数应用于 pandas 数据框的每一行,其中函数的输入是列表形式的行中的元素
how to apply a function to each row of a pandas dataframe, where the input to the function is the elements in the row in the form of a list
我想对数据框的每一行应用一个函数。该函数将数据帧的每一行作为一个列表。
例如,我正在计算一个名为 'membership' 的新列,它将数据框的整行作为输入。但是输入需要是列表的形式。以下代码无效。
df_sample['membership'] = df_sample.apply(lambda row:
cluster_pred(df_sample.values.tolist()), axis = 1)
在您的 lambda 中,您已将传入行定义为 row
,因此您只需传递 row.tolist()
:
df_sample['membership'] = df_sample.apply(lambda row:
cluster_pred(row.tolist()), axis=1)
我想对数据框的每一行应用一个函数。该函数将数据帧的每一行作为一个列表。 例如,我正在计算一个名为 'membership' 的新列,它将数据框的整行作为输入。但是输入需要是列表的形式。以下代码无效。
df_sample['membership'] = df_sample.apply(lambda row:
cluster_pred(df_sample.values.tolist()), axis = 1)
在您的 lambda 中,您已将传入行定义为 row
,因此您只需传递 row.tolist()
:
df_sample['membership'] = df_sample.apply(lambda row:
cluster_pred(row.tolist()), axis=1)