gpt4 book ai didi

Python Pandas 只能比较标记相同的系列对象

转载 作者:行者123 更新时间:2023-12-03 19:05:58 25 4
gpt4 key购买 nike

我有三个数据框。这是我的代码,我收到了值错误。raise ValueError("Can only compare identically-labeled Series objects")

ValueError: Can only compare identically-labeled Series objects.


这是我的代码:
df1
df2
df3
for i in df1: # for i from df1
x = df2.loc[df2['col_1'] == i, 'col_2'] #looking for i in col_1 of df2 and getting coresponding value of col_2 as x.
y = df3.loc[df3['col_1'] == x, 'col_2'] #looking for x in col_1 of df3 and getting coresponding value of col_2 as y
for中的第一条语句循环运行正确,但在第二条语句中出现值错误。

最佳答案

假设您的 3 个 DataFrame 具有以下内容:

df1:                df2:              df3:
Aa Bb col_1 col_2 col_1 col_2
0 123.15 12.6 0 Aa Cc 0 Cc Gg
1 137.53 28.3 1 Bb Dd 1 Dd Hh
2 Bb Ee 2 Ee Jj
3 Ff Kk
在循环的第一轮中,我包含第一列的名称
在 df1 中,即“Aa”。
当你执行 x = df2.loc[df2['col_1'] == i, 'col_2'] ,结果是
一系列的:
0    Cc
Name: col_2, dtype: object
现在,即使您尝试执行 df3['col_1'] == x ,您的错误发生了。
请注意,在这种情况下, df3['col_1'] 和 x 都是系列类型。
在这种情况下:
  • Pandas 做的第一件事就是 对齐 两个系列(在索引上),
  • 然后它会比较每对(对齐的)元素。

  • 但在这种情况下:
  • df3['col_1'] 包含索引 0 到 3,
  • x 中的索引仅包含 位置 - 0。

  • 所以出现了对齐失败,导致了这个异常。
    要解决此问题,请将违规行更改为:
    y = df3.loc[df3['col_1'].isin(x), 'col_2']
    现在 Pandas 可以按照您的预期运行:
  • 迭代 df3['col_1'],
  • 对于当前元素检查它的值是否在值之间
    存在于 x,
  • 如果是,则将当前行中 col_2 的值添加到
    结果。

  • 要演示此代码的工作原理,请使用一些打印输出完成它:
    for i in df1:
    print(f'\ni: {i}')
    x = df2.loc[df2['col_1'] == i, 'col_2']
    print(f'\nx:\n{x}')
    y = df3.loc[df3['col_1'].isin(x), 'col_2']
    print(f'\ny:\n{y}')
    当你运行上面的代码时,在我的数据上,结果是:
    i: Aa

    x:
    0 Cc
    Name: col_2, dtype: object

    y:
    0 Gg
    Name: col_2, dtype: object

    i: Bb

    x:
    1 Dd
    2 Ee
    Name: col_2, dtype: object

    y:
    1 Hh
    2 Jj
    Name: col_2, dtype: object

    关于Python Pandas 只能比较标记相同的系列对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63644575/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com