2017-10-18 148 views
1

如何從另一個數據幀引用熊貓數據幀。從另一個數據幀引用Pandas數據幀

import pandas as pd 

f1 = [['a',5,7],['b',7,9],['c',9,11],['d',11,13],['e',13,15],['f',15,17]] 
df1 = pd.DataFrame(data=f1,columns=[1,2,3]) 
f2 = [['a','c','f'],['b','d',None]] 
df2 = pd.DataFrame(data=f2, columns=[1,2,3]) 
print(df1) 
print(df2) 

我所要的輸出是另一個數據框中列出從DF1的值DF2。 輸出應該

[ 
[[5,7],[9,11],[13,15]] 
[[7,9],[11,13],[]] 
] 
+0

你想要一個列表作爲你的輸出嗎? –

+0

它可以是列表或其他數據框 – narasimman

回答

0

使第一df1與dict

df2.apply(lambda x : x.map(df1.set_index(1).T.to_dict('l'))).values.tolist() 
Out[147]: [[[5, 7], [9, 11], [15, 17]], [[7, 9], [11, 13], nan]] 

如果你想有一個數據幀

d=df2.apply(lambda x : x.map(df1.set_index(1).T.to_dict('l'))) 
d 
Out[164]: 
     1   2   3 
0 [5, 7] [9, 11] [15, 17] 
1 [7, 9] [11, 13]  NaN 

一個步驟更換NaN[]

d.loc[d[3].isnull(),3] = d.loc[d[3].isnull(),3].apply(lambda x: []) 
d 
Out[184]: 
     1   2   3 
0 [5, 7] [9, 11] [15, 17] 
1 [7, 9] [11, 13]  []