pd.merge(df1,df2,on='accountname',how='left')
或者
pd.merge(df1,df2,on='accountname',how='inner')
編輯: 讓我們看看你的樣本數據,則merge
海峽與詮釋。那爲什麼所有NaN
df1.applymap(type)
Out[96]:
email account
0 <class 'str'> <class 'str'>
1 <class 'str'> <class 'str'>
2 <class 'str'> <class 'str'>
3 <class 'str'> <class 'str'>
df2.applymap(type)
Out[97]:
account
ip
1.1.1.1 <class 'int'>
2.2.2.2 <class 'int'>
如何做到這一點:
選項1
變化str
到numeric
使用pd.to_numeric
df1.account=pd.to_numeric(df1.account,errors ='coerce')
df1.applymap(type)
Out[99]:
email account
0 <class 'str'> <class 'float'>
1 <class 'str'> <class 'float'>
2 <class 'str'> <class 'float'>
3 <class 'str'> <class 'float'>
df1.merge(df2.reset_index(),on=['account'],how='left')
Out[101]:
email account ip
0 [email protected] 555 1.1.1.1
1 [email protected] 666 2.2.2.2
2 [email protected] NaN NaN
3 [email protected] 999 NaN
選項2
我們只是改變df2.account
到str
(我更喜歡使用第一pd.to-numeric
)
df2.account=df2.account.astype(str)
df1.merge(df2.reset_index(),on=['account'],how='left')
Out[105]:
email account ip
0 [email protected] 555 1.1.1.1
1 [email protected] 666 2.2.2.2
2 [email protected] Nan NaN
3 [email protected] 999 NaN
來源
2017-10-17 21:41:08
Wen
DF3 = pd.merge(df1.dropna(),df2.dropna(),開= '帳戶名',如何=」內部「) –
你沒有accountname字段,你知道嗎? –
可以喲,請更新一個更好的數據樣本。這兩個輸入和輸出,使用[本文](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)作爲如何添加dataframs到SO – DJK