【发布时间】:2019-11-15 18:45:52
【问题描述】:
我有一个 Pandas 数据框,其中一列用于组中行的索引。我现在想根据该索引确定该行是在组的开头、中间还是结尾。我想应用一个返回开始(0)中间(1)或结束(2)作为输出的UDF,我想将每行的输出保存在一个新列中。这是我的 UDF:
def add_position_within_group(group):
length_of_group = group.max()
three_lists = self.split_lists_into_three_parts([x for x in range(length_of_group)])
result_list = []
for x in group:
if int(x) in three_lists[0]:
result_list.append(0)
elif int(x) in three_lists[1]:
result_list.append(1)
elif int(x) in three_lists[2]:
result_list.append(2)
return result_list
这里是 split_lists_into_three_parts 方法(经过试验和测试):
def split_lists_into_three_parts(self, event_list):
k, m = divmod(len(event_list), 3)
total_list = [event_list[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(3)]
start_of_list = total_list[0]
middle_of_list = total_list[1]
end_of_list = total_list[2]
return [start_of_list,middle_of_list,end_of_list]
这是对 Dataframe 进行分组并运行 transform() 的代码行,根据我所阅读的内容,当在 groupby 上调用它时,它会遍历所有组并将列作为一个系列作为参数并应用我的UDF。它必须返回与组相同大小的一维列表或系列。:
compound_data_frame["position_in_sequence"] = compound_data_frame.groupby('patient_id')["group_index"].transform(self.add_position_within_group)
我收到以下错误:
shape mismatch: value array of shape (79201,) could not be broadcast to indexing result of shape (79202,)
我仍然无法弄清楚我的函数在传递给转换时必须具有什么样的输出,或者为什么我会收到此错误。任何帮助将非常感激。
【问题讨论】:
-
if ... elif ... elif ... else? -
很好的调用,可能是结果列表因此而缺少值
标签: python pandas dataframe transform