【问题标题】:Keying Error: 'Series' objects are mutable, thus they cannot be hashed键控错误:“系列”对象是可变的,因此它们不能被散列
【发布时间】:2021-01-17 19:07:42
【问题描述】:

刚开始使用 Python 并遇到此错误。

我有两个数据框 A 和 B。我使用其中一个输入列来键入 A,然后将两者结合起来,我想键入 B。我在第二个打印步骤中遇到错误。我确实查看了其他类似的线程,但没有找到解决方案。你能帮我修一下吗?

import pandas as pd
A = pd.DataFrame([
    {"AC1":"V1", "AC2":"190801"},
    {"AC1":"V2", "AC2":"200414"},
    ])
A = A.set_index("AC1")

B = pd.DataFrame([
    {"BC1":"V1","BC2":"190801","BC3":"2019-10-01"},
    {"BC1":"V1","BC2":"191201","BC3":"2019-12-01"},
    {"BC1":"V2","BC2":"200414","BC3":"2020-01-24"}
    ])
B["BC3"] = pd.to_datetime(B["BC3"])
B = B.set_index(["BC1","BC2"])

input = pd.DataFrame([
    {"X":"V1","State":"FL","Z":100},
    {"X":"V2","State":"CA","Z":130},
    ])

for item in input["X"].unique():
    p1 = A.loc[item]
    print(p1)
    p2 = B.loc[[(item,p1)],"BC3"]
    print(p2)

TypeError: 'Series' 对象是可变的,因此它们不能被散列

【问题讨论】:

标签: python pandas indexing


【解决方案1】:

如果我理解正确,您想使用“输入”数据帧的 X 列的每个唯一值,在 A 数据帧中查找,从中获取 AC2 值,然后使用X 加上 AC2 的值以在 B 数据帧中查找 BC3 中的值。对吗?

如果是这样,您只需在以p1 = 开头的行中添加一个列选择器,并从以p2 = 开头的行中删除一组括号

这对我有用:

for item in input["X"].unique():
    p1 = A.loc[item, "AC2"]
    print(p1)
    p2 = B.loc[(item, p1), "BC3"]
    print(p2)

我从中得到以下输出:

190801
2019-10-01 00:00:00
200414
2020-01-24 00:00:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多