今天处理数据的时候需要对DataFrame的两列做笛卡积操作,一开始使用merge方法,奈何一直爆内存,只能用for循环的形式来写,只是这样的速度实在太慢。先用笨办法解决掉吧,记录一下,有没有兄台有更巧妙地方法,还请不吝赐教啊。
match = pd.read_csv('../input/match.csv')
match.head()
image.png
方法一 :时间换空间
def merge_match(match):
A = pd.DataFrame(match['paper_id'])
B = pd.DataFrame(match['press_id'])
A.columns = ['paper_id']
B.columns = ['press_id']
newDf = pd.DataFrame(columns=['paper_id','press_id','labels'])
for i, A_row in A.iterrows():
for j, B_row in B.iterrows():
Adata = A_row['paper_id']
Bdata = B_row['press_id']
if i == j :
label = 1
else:
label = 0
row = pd.DataFrame([dict(paper_id=Adata,press_id=Bdata,labels=label)])
newDf = newDf.append(row,ignore_index=True)
return newDf
方法二 : 空间占用较大,速度快
def merge_match(match):
A = pd.DataFrame(match['paper_id']
B = pd.DataFrame(match['press_id']
A['value'] = 1
B['value'] = 1
newDf = pd.merge(A,B,on='value')
return newDf
网友评论