Python Pandas - 合并列表中每个项目的数据帧

标签 python pandas

假设我有表“销售”:

          ProductId   Sales
0               [1]   $199
1               [2]   $299
2         [3, 4, 5]   $399
3         [6, 7, 8]   $499

和表“产品”:

        ID            Product
0       1                   A
1       2                   B
2       3                   C
3       4                   D
4       5                   E
5       6                   F
6       7                   G
7       8                   H

我想返回一个新表“sales_product”

            Product   Sales
0                 A   $199
1                 B   $299
2             C,D,E   $399
3             F,G,H   $499

因此它可以找到所有匹配的 ProductId 并在新表中以逗号连接的字符串形式返回 Product 值。

任何 Python 方法都可以实现这一点吗?

最佳答案

让我们试试这个,使用 IDProduct 创建一个查找,然后将其映射回 sales 数据集。

# {1: 'A', 2: 'B', 3: 'C'...}
lookup = product.set_index("ID")['Product'].to_dict()

sales['Product'] = sales.ProductId.apply(
    lambda x: ",".join([lookup[v] for v in x if lookup.get(v)])
)

  Product Sales
0       A  $199
1       B  $299
2   C,D,E  $399
3   F,G,H  $499

关于Python Pandas - 合并列表中每个项目的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62976836/

相关文章:

python - 将 Numpy 数组转换为 Pandas DataFrame

python - ValueError : Wrong number of items passed 5, 放置意味着 1

python - 嵌套 json 到 Pandas 非常慢

python - 使用 Python 的 MQTT 和 SQLite3 通信

python - 如何覆盖 createView 以保存多个数据条目

python - 如何使用标签中包含 '-' 连字符的列的 pd.DataFrame 对象的查询方法?

python - 不知道如何根据条件合并数据

python - pandas:如何查询多级列数据框?

python - crontab 自动 python 脚本不会上传到 dropbox

python - 适用于桉树云的 boto 版本