2017-02-23 50 views
1

我有2個不同的數據框。 第一個是這樣的:熊貓數據框查找不同數據框中的值並指定值

 joint label  x z  y pt 
0  1 NaN 50.4 0.0 -8.40 10 
1  2 shell 52.2 0.0 -8.40 20 
2  3 shell 54.0 0.0 -8.40 30 
3  4 shell 55.8 0.0 -8.40 40 
4  5 shell 57.6 0.0 -8.40 50 

和我的第二個數據幀的樣子:

 member joint1 joint2  joint1_pt  joint2_pt 
0   1  1  2    0    0 
1   2  2  3    0    0 
2   3  3  4    0    0 
3   4  4  5    0    0 

我想採取使用PT值是在一個特定的jointe對應和使用第二個數據幀如下所示:

 member joint1 joint2  joint1_pt  joint2_pt 
0   1  1  2    10    20 
1   2  2  3    20    30 
2   3  3  4    30    40 
3   4  4  5    40    50 

你能幫我一個例子/理想我該如何解決這個問題? 提前謝謝!

+0

你可以用'pd.DataFrame.to_dict' (像[這](http://stackoverflow.com/questions/18012505/python-pandas-dataframe-columns-convert-to-dict-key - 和值))和'pd.Series.map'(如[this](http://stackoverflow.com/questions/35561517/mapping-values-into-a-new-dataframe-column))。 –

回答

2

你需要mapSeriesset_indexto_dict創建dict爲指向P-robot的評論:

d = df1.set_index('joint')['pt'].to_dict() 
#mapping by Series works, but a bit slowier 
#d = df1.set_index('joint')['pt'] 
print (d) 
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50} 

df2['joint1_pt'] = df2['joint1'].map(d) 
df2['joint2_pt'] = df2['joint2'].map(d) 
print (df2) 
    member joint1 joint2 joint1_pt joint2_pt 
0  1  1  2   10   20 
1  2  2  3   20   30 
2  3  3  4   30   40 
3  4  4  5   40   50 
+0

我嘗試實現你的代碼,我得到NaN在joint1_pt和joint2_pt列 –

+0

檢查dtypes,可能需要轉換爲str或int,如'df2 ['joint1_pt'] = df2 ['joint1']。astype(str).map(d)'或'df2 ['joint1_pt'] = df2 ['joint1 '] .astype(int).map(d)'因爲需要相同。 – jezrael

+0

在字典和列joint1和join2中相同。 – jezrael

3

您可以使用merge合併後將pt分配給joint1_pt & joint2_pt,最後刪除不需要的列。

df= pd.merge(df2,df1[['joint','pt']], right_on='joint',left_on='joint1',how='left') 
df= pd.merge(df,df1[['joint','pt']], right_on='joint',left_on='joint2',how='left') 
df[['joint1_pt','joint2_pt']] =df[['pt_x','pt_y']] 
df=df[['member','joint1','joint2','joint1_pt','joint2_pt']] 
print df 

輸出

member joint1 joint2 joint1_pt joint2_pt 
0  1  1  2   10   20 
1  2  2  3   20   30 
2  3  3  4   30   40 
3  4  4  5   40   50 
+0

df1 ['joint','pt']似乎不起作用。我得到一個KeyError :('joint','pt')。即使當我嘗試打印這不起作用。但是,當我嘗試單獨打印它時,它可以正常工作。任何想法? –

+0

我剛剛編輯答案 – Shijo

+0

感謝您的協助!它的工作原理沒有給出錯誤,但是你有什麼想法爲什麼它爲joint1_pt和joint2_pt列中的所有條目返回一個NaN? –