簡體   English   中英

大熊貓:根據其他數據框創建數據框列

[英]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中的值在d​​f1中添加一列。 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結果mapdf1 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM