[英]Fastest way to transform dataframe
我有一個3列的數據框:
reading_df:
c1 c2 c3
1 1 0.104986
1 1 0.628024
0 0 0.507727
1 1 0.445931
0 1 0.867830
1 1 0.455478
1 0 0.271283
0 1 0.759124
1 0 0.382079
0 1 0.572290
對於第3列(c3)中的每個元素,我必須找到多少個項目(行):
例如,在c4列中編寫答案
c1 c2 c3 c4
1 1 0.104986 0
1 1 0.628024 2
0 0 0.507727 0
1 1 0.445931 0
0 1 0.867830 2
1 1 0.455478 1
1 0 0.271283 0
0 1 0.759124 1
1 0 0.382079 1
0 1 0.572290 0
我將數據幀轉換為numpy數組,並將映射函數與labmda結合使用以具有最佳性能。
reading_df['c4']=np.zeros(df.shape[0])
X=np.array(reading_df)
c1=0
c2=1
c3=2
dT=0.3
res_map = map(lambda el: len( X[
( X[:,n_time] > (el[n_time]-dT) )
& ( X[:,n_time] < (el[n_time]) )
& ( X[:,n_feature2] == (el[n_feature2]) )
& ( X[:,n_feature1] == (el[n_feature1]) )
][:,n_time]), X)
但是當我嘗試將地圖對象res_map
轉換為列表時:
result=list(res_map)
result_dataframe=pd.DataFrame({'c4':result })
我的代碼變得非常慢。 對於具有1 * 10 ^ 6個以上元素的大數據幀,它需要花費很長時間。
我必須使用哪個功能? 哪些最佳實踐可以使python更快地工作?
不知道問題背后的確切邏輯是什么,但我認為您想groupby
並計算diff
如果我正確理解了您的問題,則它在c1
和c2
每個組中many-to-many
比較。
這是您可以建立的問題的起點:
# first calculate the difference between rows in c3 column while applying groupby
df['difference'] = df.groupby(['c1', 'c2']).c3.diff()
# then add a count column which counts the size of each group
df['count'] = df.groupby(['c1', 'c2']).c1.transform('count')
# after that create a conditional field based on the values in the other columns
df['c4'] = np.where((df.c1 == df.c2) & (df.difference < 0.3), 1, 0)
希望這對速度(向量化)有幫助,並能更進一步解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.