【问题标题】:Index match in Pandas?Pandas 中的索引匹配?
【发布时间】:2020-11-28 13:05:05
【问题描述】:

我正在尝试根据行键和列键匹配 x 值。在 excel 中,我使用 INDEX & MATCH 来获取正确的值,但在 Pandas 中我很难做到这一点。

示例:

我想将突出显示的值(保存在 df2 中)添加到我的 df['Cost'] 列中。

我有 df['Weight'] & df['Country'] 作为键,但我不知道如何使用它们来查找 df2 中突出显示的值。

如何将黄色值提取到 df3['Postage'] 中,然后我可以将其添加到我的 df['Cost'] 列中?

我希望这是有道理的。让我知道我应该提供更多信息。

编辑 - 更多信息(抱歉,我不知道如何从 Jupyter 复制输出):

当我运行 [93] 时,我收到以下错误:

ValueError: Row labels must have same size as column labels

谢谢!

【问题讨论】:

  • 请提供一些您的数据帧示例(df2、df3 等)
  • 向我们展示 python pandas dataframe 中的示例
  • 行列索引称为lookup,类似于excel。
  • 谢谢,我添加了更多信息。让我知道这是否有帮助。

标签: python python-3.x pandas jupyter-notebook


【解决方案1】:

简单地获取突出显示的值1.75

df2.loc[df2['Country']=='B', 3]

因此,概括上述内容并使用来自df1 的国家权重密钥对:

cost = []

for i in range(df1.shape[0]):
    country = df1.loc[i, 'Country']
    weight = df1.loc[i, 'Weight']
    cost.append(df2.loc[df2['Country']==country, weight]

df1['Cost'] = cost

或者更好:

df1['Cost'] = df1.apply(lambda x: df2.loc[df2['Country']==x['Country'], x['Weight'], axis=1)

【讨论】:

  • 非常感谢!你最后的回答对我有帮助!起初我无法使用它,因为行权重(int)正在查看列(str)。将重量转换为物体似乎有所帮助!
【解决方案2】:

供您使用(注意 [0] 需要索引到数组中)

row = df1.iloc[1]
df2[df2.Country == row.Country][row.Weight][0]

希望这对 .iloc 和 .loc 有所帮助

d = {chr(ord('A')+r):[c+r*10 for c in range(5)] for r in range(5)}
df = pd.DataFrame(d).transpose()
df.columns=['a','b','c','d','e']
print(df)
print("--------")
print(df.loc['B']['c'])
print(df.iloc[1][2])

输出

    a   b   c   d   e
A   0   1   2   3   4
B  10  11  12  13  14
C  20  21  22  23  24
D  30  31  32  33  34
E  40  41  42  43  44
--------
12
12

【讨论】:

  • 谢谢,不幸的是我收到以下错误:TypeError: Cannot index by location index with a non-integer key
  • (Tks to @Leonardus Chen) - 修复了使用 df.Countr == row.Country 查找行。然后按行索引到 arr.Weight 值...然后返回 [0] 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
相关资源
最近更新 更多