[英]Merging a pandas DataFrame with a Series
我有這個df:
cnpj
0 33062217000185
1 82645144000160
我運行一個創建兩個不同系列的函數:
for i in df.cnpj:
s=peer_comparison(i)
df=df.merge(peers.to_frame().T, how='left', on='cnpj')
在for語句的第一輪中,輸出序列如下所示:
s (first round):
A N/A
B N/A
C N/A
cnpj 33062217000185
合並的數據框如下所示:
cnpj A B C
0 33062217000185 N/A N/A N/A
1 82645144000160 NaN NaN NaN
當進行第二輪合並時,該系列如下所示:
s (second round):
A N/A
B N/A
C N/A
cnpj 82645144000160
但是合並變得一團糟,就像這樣:
cnpj A_x B_x C_x A_y B_y C_y
0 33062217000185 N/A N/A N/A NaN NaN NaN
1 82645144000160 NaN NaN NaN N/A N/A N/A
如果我嘗試使用df.merge(s.to_frame().T.astype({'cnpj' : 'int'}), how='left',on='cnpj').fillna('')
更改合並df.merge(s.to_frame().T.astype({'cnpj' : 'int'}), how='left',on='cnpj').fillna('')
出現以下錯誤:
ValueError: entry not a 2- or 3- tuple
有人可以幫忙嗎?
設定
df = pd.DataFrame({'cnpj': [33062217000185, 82645144000160]})
print(df)
cnpj
0 33062217000185
1 82645144000160
s = pd.Series(['N/A', 'N/A', 'N/A', 33062217000185], index=['A', 'B', 'C', 'cnpj'])
print(s)
A N/A
B N/A
C N/A
cnpj 33062217000185
dtype: object
使用df.merge
,將s
轉換為數據幀並在過程df.merge
置。
df.merge(s.to_frame().T\
.astype({'cnpj' : 'int'}), how='left').fillna('')
cnpj A B C
0 33062217000185 N/A N/A N/A
1 82645144000160
獲得一些@COLDSPEED技巧並使用concat而不是合並或加入它終於可以了。
peers=peer_comparison(df.cnpj[0])
for i in df.cnpj[1:]:
peers2=peer_comparison(i,base_year)
peers=pd.concat([peers,peers2],axis=1)
df=peers.T
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.