請考慮以下DataFrame df:timestamp id condition 1234 A 2323 B 3843 B 1234 C 8574 A 9483 A基于列條件中包含的條件,我必須在此數(shù)據(jù)框中定義一個新列,該列計算該條件中有多少個id。但是,請注意,由于DataFrame是由timestamp列排序的,因此可能會有多個具有相同id的條目,然后簡單的.cumsum()并不是可行的選擇。我已經(jīng)給出了以下代碼,該代碼可以正常運行,但是速度非常慢:#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數(shù)組對我來說非常有用,因為它會給出特定條件下的ID列表。我也可以將這些數(shù)組動態(tài)地放入df DataFrame中的相應單元格中。您是否能夠提出更好的性能解決方案?
添加回答
舉報
0/150
提交
取消