如何有条件地在熊猫数据框中做一个vlookup
问题描述:
我想弄清楚如何做一个vlookup来挑选出最新的价格来填补第二张表。下面的例子。对于项目#1,最新价格在月份6 (=$6)
,而项目#2在月份5 (=$4)
。填表B的最佳方式是什么?注意:如果该项目是新的,则有可能在表A中找不到item_id
。如何有条件地在熊猫数据框中做一个vlookup
任何指导?非常感谢。
表A(参考)
| Item_ID | Month | Price |
|---------|-------|-------|
| 1 | 4 | 10 |
| 1 | 5 | 8 |
| 1 | 6 | 6 |
| 2 | 5 | 4 |
表B(填充)
| Shop_ID | Item_ID | Price |
|---------|---------|-------|
| 1 | 1 | 6 |
| 1 | 2 | 4 |
答
你可以先找到最新的信息,然后将其合并到创建表:
import pandas
tableA = pandas.DataFrame({'Item_ID': {0: 1, 1: 1, 2: 1, 3: 2},
'Month': {0: 4, 1: 5, 2: 6, 3: 5},
'Price': {0: 10, 1: 8, 2: 6, 3: 4}})
tableB = pandas.DataFrame({'Item_ID': {0: 1, 1: 2},
'Price': {0: 6, 1: 4},
'Shop_ID': {0: 1, 1: 1}})
latest = tableA.loc[tableA.groupby('Item_ID')['Month'].idxmax()]
result = tableB[['Shop_ID', 'Item_ID']].merge(latest[['Item_ID', 'Price']],
on='Item_ID')
这就产生
Shop_ID Item_ID Price
0 1 1 6
1 1 2 4
答
要df2
填写列Price
我们可以创建一个熊猫系列的Item_ID和价格。对于每个Item_ID
,使用drop_duplicates
作为最后一行,并通过set_index
创建Series
并选择列。最后用map
创建新列。
完整的示例:
import pandas as pd
# Sample data
data1 = dict(Item_ID=[1,1,1,2], Month=[4,5,6,5], Price = [10,8,6,4])
data2 = dict(Shop_ID=[1,1],Item_ID=[1,2])
# Create dfs
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# Crete a series with Item_ID as index and Price as value
s = df1.drop_duplicates('Item_ID', keep='last').set_index('Item_ID')['Price']
# Create new column in df2
df2['Price'] = df2['Item_ID'].map(s)
print (df2)
返回:
Shop_ID Item_ID Price
0 1 1 6
1 1 2 4
更多详情
如果需要使用sort_values
第一
s = (df1.sort_values(['Item_ID','Month'])
.drop_duplicates('Item_ID', keep='last')
.set_index('Item_ID')['Price'])
意甲s
看起来是这样的:
Item_ID
1 6
2 4
Name: Price, dtype: int64
这个答案很好,冒昧添加一些数据并且扔东西+1 –
@AntonvBR - 非常感谢。 – jezrael