请考虑以下DataFrame df:timestamp id condition 1234 A 2323 B 3843 B 1234 C 8574 A 9483 A基于列条件中包含的条件,我必须在此数据框中定义一个新列,该列计算该条件中有多少个id。但是,请注意,由于DataFrame是由timestamp列排序的,因此可能会有多个具有相同id的条目,然后简单的.cumsum()并不是可行的选择。我已经给出了以下代码,该代码可以正常运行,但是速度非常慢:#I start defining empty arraysids_with_condition_a = np.empty(0)ids_with_condition_b = np.empty(0)ids_with_condition_c = np.empty(0)#Initializing new columndf['count'] = 0#Using a for loop to do the task, but this is sooo slow!for r in range(0, df.shape[0]): if df.condition[r] == 'A': ids_with_condition_a = np.append(ids_with_condition_a, df.id[r]) elif df.condition[r] == 'B': ids_with_condition_b = np.append(ids_with_condition_b, df.id[r]) ids_with_condition_a = np.setdiff1d(ids_with_condition_a, ids_with_condition_b) elifif df.condition[r] == 'C': ids_with_condition_c = np.append(ids_with_condition_c, df.id[r])df.count[r] = ids_with_condition_a.size保留这些Numpy数组对我来说非常有用,因为它会给出特定条件下的ID列表。我也可以将这些数组动态地放入df DataFrame中的相应单元格中。您是否能够提出更好的性能解决方案?
添加回答
举报
0/150
提交
取消
