![](/img/trans.png)
[英]Pandas lookup, mapping one column in a dataframe to another in a different dataframe
[英]Mapping column from one pandas DataFrame to another
我有一個像這樣的 dataframe:
df_1 = pd.DataFrame({'players.name': ['John', 'Will' ,'John', 'Jim', 'Tim', 'John', 'Will', 'Tim'],
'players.diff': [0, 0, 0, 0, 0, 0, 0, 0],
'count': [3, 2, 3, 1, 2, 3, 2, 2]})
'count' 值是恆定的。
而且我有一個不同的形狀 dataframe 與球員訂購不同,像這樣:
df_2 = pd.DataFrame({'players.name': ['Will', 'John' ,'Jim'],
'players.diff': [0, 0, 0]})
我如何從df_1
值 map 並在df_2
上填充“計數”值,最終得到:
players.name players.diff counts
0 Will 0 2
1 John 0 3
2 Jim 0 1
由於您只是嘗試創建一列計數,因此對map
您的玩家名稱計數更有意義:
df_2['counts'] = df_2['players.name'].map(
df_1.groupby('players.name')['count'].first())
df_2
players.name players.diff counts
0 Will 0 2
1 John 0 3
2 Jim 0 1
您的示例df_1
具有相同數量的重復players.name
,因此您需要 left-merge 和 drop_duplicates
new_df_2 = df_2.merge(df_1[['players.name','count']], on='players.name', how='left').drop_duplicates()
Out[89]:
players.name players.diff count
0 Will 0 2
2 John 0 3
5 Jim 0 1
這可以工作:
pd.merge(df_1, df_2, on=["players.name", "players.diff"]).drop_duplicates()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.