![](/img/trans.png)
[英]Create a new pandas dataframe column based on other column of the dataframe
[英]Pandas: Create dataframe column based on other dataframe
如果我有兩個像這樣的兩個數據框:
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很長,因此我需要一些有效的東西(我在一個循環中嘗試過,但這要花很多時間)。
您可以使用to_dict
方法從df2
創建dict
,然后map
結果map
到df1
Type
列:
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
根據要求,我發布了一個使用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
這依賴於以下InvalidIndexError: Reindexing only valid with uniquely valued Index objects
正在查找的鍵值存在,否則我們將得到KeyError
並且df2
沒有重復的條目,否則設置索引會引發InvalidIndexError: Reindexing only valid with uniquely valued Index objects
另一種方法是使用基於標簽的索引器loc
。 首先使用Type
列的索引使用.set_index
,然后訪問使用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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.