有檔案A:
,B:
,希望通過A,B生成C:
就是笛卡爾積操作。
一,當資料在numpy數組中,資料為:
A=['a','b','c','d']
B=['1','2','3','4']
其實方法一的思想很簡單粗暴:A,B元素存儲在list中,将A中每個元素複制len(B)次,然後将之與B進行行合并;得到的結果再與result列合并。最後輸出result
代碼如下:
def dikaerji(A,B):
lenB = len(B)
# print(lenB)
dika_num = pd.DataFrame(columns=['alph','num'])
for a in A:
curA = np.array([a]*lenB)
curA.shape = (lenB,)
# 必須要先轉換成np的aray形式,不然會報“沒有shape”的錯
curB = np.array(B)
curB.shape = (lenB,)
join_h = np.hstack((curA,curB))
dika_num = dika_num.append(pd.DataFrame(join_h,columns=['alph','num']),ignore_index=True)
return dika_num
結果為:
方法二,若資料是在兩個DataFrame中存儲着:
first = DataFrame([['a','b','c','d']],columns=['first'])
second = DataFrame([,,,],columns=['second'])
思想:循環周遊兩層for循環,使用iterrows()函數來擷取行資訊,代碼如下:
def getMergeAB(A,B):
newDf = DataFrame(columns=['alpha','nums'])
for _,A_row in A.iterrows():
for _,B_row in B.iterrows():
AData=A_row['first']
BData=B_row['second']
row = DataFrame([dict(alpha=AData,nums=BData)])
newDf = newDf.append(row,ignore_index=True)
return newDf
測試:
first = DataFrame([['a','x'],['b','y'],['c','z'],['d','w']],columns=['first','x_first'])
second = DataFrame([,,,],columns=['second'])
da = getMergeAB(first,second)
結果:
說明:A.iterrows()函數傳回一個(index, Series) pairs,存儲的是這一行的下标值和這一行所有的值