2016-08-05 97 views
1

數據框柱如果我有2個dataframes喜歡這兩個:熊貓:創建基於其他數據框

import pandas as pd 

df1 = pd.DataFrame({'Type':list('AABAC')}) 
df2 = pd.DataFrame({'Type':list('ABCDEF'), 'Value':[1,2,3,4,5,6]}) 

    Type 
0 A 
1 A 
2 B 
3 A 
4 C 

    Type Value 
0 A  1 
1 B  2 
2 C  3 
3 D  4 
4 E  5 
5 F  6 

我想補充的基礎上DF2的值DF1列。 df2僅包含唯一值,而df1具有每個值的多個條目。 所以導致DF1應該是這樣的:

Type Value 
0 A  1 
1 A  1 
2 B  2 
3 A  1 
4 C  3 

我的實際數據幀DF1是很長,所以我需要的東西是有效的(我試過在一個循環,但這需要永遠)。

+0

by'the values'你只是指df2中的'Value'列嗎? –

+2

有很多類似的問題和方法,你認爲'merge'例如? – EdChum

+0

是的,正是基於'價值'一欄 – petetheat

回答

2

你可以從你的df2創建dictto_dict方法,然後map結果Typedf1

replace_dict = dict(df2.to_dict('split')['data']) 

In [50]: replace_dict 
Out[50]: {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6} 

df1['Value'] = df1['Type'].map(replace_dict) 

In [52]: df1 
Out[52]: 
    Type Value 
0 A  1 
1 A  1 
2 B  2 
3 A  1 
4 C  3 
+2

的初始順序,你可以在df2上設置索引'Type',所以df1 ['Value'] = df1 ['Type']。map(df2.set_index('Type')['Value' ])'也可以工作 – EdChum

+0

@EdChum這與上面的例子一起工作,但不能與我的完整數據集'pandas.core.index.InvalidIndexError:Reindexing只對唯一有價值的索引對象有效' – petetheat

+0

它可以幫助我們,如果你發佈一個有代表性的例子來停止浪費我們的時間來幫助你,如果你發佈一個簡單的例子,你會得到一個簡單的答案。發表一個代表性的例子或你的真實數據 – EdChum

2

按照要求我張貼,使用map,而無需創建一個臨時的字典的解決方案:

In[3]: 
df1['Value'] = df1['Type'].map(df2.set_index('Type')['Value']) 
df1 

Out[3]: 
    Type Value 
0 A  1 
1 A  1 
2 B  2 
3 A  1 
4 C  3 

這依賴於一對夫婦,被查找的關鍵值存在erwise我們得到一個KeyError和我們沒有在df2重複條目,否則設置索引提高InvalidIndexError: Reindexing only valid with uniquely valued Index objects

0

另一種方式做,這是通過使用基於索引loc的標籤。首先使用.set_index使用Type列索引,然後訪問使用df1列,並重置指數爲原始與.reset_index

df2.set_index('Type').loc[df1['Type'],:].reset_index() 

要麼將​​此作爲新的df1或提取Value柱:

df1['Value'] = df2.set_index('Type').loc[df1['Type'],:].reset_index()['Value']