我正在尝试弄清楚如何进行 vlookup 来挑选最新价格来填充第二个表。下面是一个例子。对于商品 #1,最新价格为 6 (=$6)
,商品 #2 的最新价格为 5 (=$4)
。填写表 B 的最佳方式是什么?注意:如果项目是新的,则可能会在表 A 中找不到 item_id
。
有什么指导吗?非常感谢。
表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 |
最佳答案
要填充 df2
中的 Price
列,我们可以使用 Item_ID 和 Price 创建一个 Pandas 系列。使用drop_duplicates
对于每个 Item_ID
的最后一行,并通过 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
关于python - 如何在 Pandas 数据框中有条件地进行 vlookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47485810/