【问题标题】:Taking a cross product of Pandas Dataframes取 Pandas Dataframes 的叉积
【发布时间】:2019-09-12 17:45:05
【问题描述】:

我正在尝试从一个数据帧中获取字符串数据并将其替换为数值并创建结果的叉积,如下所示。

我将数据读入数据帧,示例输入如下:

import pandas as pd
shoppers = pd.DataFrame({'name': ['bill', 'bob', 'james', 'jill', 'henry'], 
                         'item': ['apple','apple','orange','grapes','orange']})

stores = pd.DataFrame({'apple' : [0.25, 0.20, 0.18], 
                       'orange': [0.30, 0.4, 0.35],
                       'grapes': [1.0, 0.9, 1.1], 
                       'store':  ['kroger', 'publix', 'walmart']})

这是生成的购物者数据框:

         item
name         
bill    apple
bob     apple
james  orange
jill   grapes
henry  orange

这是生成的商店数据框:

         apple  orange  grapes
store                         
kroger    0.25    0.30     1.0
publix    0.20    0.40     0.9
walmart   0.18    0.35     1.1

期望的结果是每个人在每家商店支付的价格。例如:

我真的很难找到正确的方法来有效地在 Pandas 中进行这种转换。我可以轻松地遍历购物者和商店,并以蛮力的方式构建每一行,但必须有一种更有效的方法来使用 pandas API 来做到这一点。感谢您的任何建议。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这里有一个解决方案,不是cross,而是dot

    pd.crosstab(shoppers.index, shoppers['item']).dot(stores.T)
    

    输出:

           kroger  publix  walmart
    row_0                         
    bill     0.25     0.2     0.18
    bob      0.25     0.2     0.18
    henry    0.30     0.4     0.35
    james    0.30     0.4     0.35
    jill     1.00     0.9     1.10
    

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2018-05-16
      • 2019-10-18
      相关资源
      最近更新 更多