[英]Pandas apply custom function to each dataframe row and append results
[英]Faster way to apply custom function to each row in pandas dataframe?
我有兩個數據框ad_df,x_df 。 我創建了一個函數find_ids取入的ID ad_id和從ad_df日期ad_date。
該函數通過以下內容過濾x_df
然后,我將結果數據框附加到跟蹤這些行的全局數據框res_df中。
我通過使用以下行來調用該函數:
ad_df.apply(lambda x: find_units_moved(x['SerialNo'],x['Audit Date'] ), axis = 1)
有更快的方法嗎? ad_df大約有100萬行,因此希望有一種更快的方法。 該功能的代碼如下所示。
def find_ad_ids(ad_id, ad_date):
id_specific_df = x_df.loc[x_df['ID'] == ad_id]
beg_range_date = ad_date - timedelta(days = 2)
end_range_date = ad_date + timedelta(days = 15)
beg_df = id_specific_df[(id_specific_df['Last_Date'] > beg_range_date) & (id_specific_df['Last_Date'] < ad_date)]
end_df = id_specific_df[(id_specific_df['Last_Date''] > ad_date) & (id_specific_df['Last_Date'] < end_range_date)]
if(len(beg_df.columns) != 0 and len(end_df.columns) != 0):
if(('1' in beg_df['Geo_Label'].array) and ('1' in end_df['Geo_Label'].array)):
res_df.append(pd.concat([beg_df, end_df], ignore_index=True))
將數據追加到數據框的最快方法之一是通過dict:
startTime = time.perf_counter()
row_list = []
for i in range (0,5):
row_list.append(dict( (a,np.random.randint(100)) for a in ['A','B','C','D','E']))
for i in range( 1,numOfRows-4):
dict1 = dict( (a,np.random.randint(100)) for a in ['A','B','C','D','E'])
row_list.append(dict1)
df4 = pd.DataFrame(row_list, columns=['A','B','C','D','E'])
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df4.shape)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.