【问题标题】:how to compare two values in series, not the series objects? Python 3.x如何比较系列中的两个值,而不是系列对象? Python 3.x
【发布时间】:2017-02-01 00:28:58
【问题描述】:

我收到一条错误消息,提示“ValueError:只能比较标签相同的 Series 对象”。据我所知,我正在比较两个系列对象而不是它们内部的值。然而,我认为series[column] 给了你内在的价值。有人可以详细说明一下吗?我真的被困在哪里可以找到这些信息,并且很乐意被指向正确的方向。 all_agesrecent_grads 是数据帧。

import pandas as pd

majors = recent_grads['Major'].unique()
rg_lower_count = 0

for x in majors:
    aa_major = all_ages[all_ages['Major'] == x]
    rg_major = recent_grads[recent_grads["Major"] == x]


    if rg_major["Unemployment_rate"] < aa_major["Unemployment_rate"]:
        rg_lower_count += 1

print(rg_lower_count)

【问题讨论】:

  • rg_majoraa_major 必须具有不同的索引,这可能就是问题所在。在比较之前,您可能必须在 aa_majorrg_major 上应用 .reset_index。此外,您可能必须在此处修复缩进。 if-statement 可能需要在 for-loop 内。
  • @Abdou 谢谢你修复了缩进。当我做.reset_index 时,它不适合我,但我会更多地使用它,看看我是否能让它工作。感谢您的反馈。
  • 我用这段代码玩了更多,if语句有两种工作方式:if float(series[column]) &lt; float(series[column]):if series[column].item() &lt; series[column].item()

标签: python pandas compare series


【解决方案1】:

See this old question of mine

你不能再这样做了。当您比较 &lt;&gt; 时,您需要将索引对齐reindex 你的一个系列和另一个系列一样。

我会像这样编辑你的代码

import pandas as pd

majors = recent_grads['Major'].unique()
rg_lower_count = 0

for x in majors:
    aa_major = all_ages[all_ages['Major'] == x]
    rg_major = recent_grads[recent_grads["Major"] == x]

rg_major_unemp = rg_major["Unemployment_rate"]
aa_major_unemp = aa_major["Unemployment_rate"].reindex_like(rg_major_unemp)

if rg_major_unemp < aa_major_unemp:
    rg_lower_count += 1

print(rg_lower_count)

演示

与链接问题中的示例相同

import pandas as pd
x = pd.Series([1, 1, 1, 0, 0, 0], index=['a', 'b', 'c', 'd', 'e', 'f'], name='Value')
y = pd.Series([0, 2, 0, 2, 0, 2], index=['c', 'f', 'a', 'e', 'b', 'd'], name='Value')

x > y
ValueError: Can only compare identically-labeled Series objects
x.reindex_like(y) > y

c     True
f    False
a     True
e    False
b     True
d    False
Name: Value, dtype: bool

【讨论】:

  • 这对我很有用。我不知道.reindex_like 属性,但我认为它很有用。但是,在我这样做之前,我设法通过if float(series[column]) &lt; float(series[column]): 让我的代码工作,我不知道这是否是解决此问题的正确方法?
猜你喜欢
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多