为什么这个价值变得模棱两可?

时间:2017-02-21 13:15:42

标签: python pandas dataframe

我完全混淆了为什么我在这段代码上得到了一个ValueError;任何帮助表示感谢。

我有一个名为global_output的数据框,有两列:一列单词和相应值的列。我想对值进行中值分割,并将单词分为两个列表 - 高和低 - 取决于它们是高于还是低于中位数。

       Word         Ranking
0      shuttle      0.9075
1      flying       0.7750
2      flight       0.7250
3      trip         0.6775
4      transport    0.6250
5      escape       0.5850
6      trajectory   0.5250
7      departure    0.5175
8      arrival      0.5175

我这样做的代码如下:

split = global_output['Abstraction'].quantile([0.5])

high = []
low = []


for j in range(len(global_output)):
    if global_output['Ranking'][j] > split:
        low_clt.append(global_output['Word'][j])
    else:
        high.append(global_output['Word'][j])

但是,我一直收到这个错误。

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

现在,我理解错误意味着什么:它说我正在尝试评估具有多个值的系列,就像它是单个值一样。不过,我只是看不出怎样

global_output['Ranking'][j]
当j从循环中取整数值时,

以任何方式都是不明确的。当我将它输入控制台时,它每次都会产生一个浮点值。我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您正在使用arrays,因此最好使用boolean indexingmaskloc来选择列:

#if need column Abstraction, change it
split = global_output['Ranking'].quantile([0.5]).item()
print (split)
0.625

mask = global_output['Ranking'] <= split
print (mask)
0    False
1    False
2    False
3    False
4     True
5     True
6     True
7     True
8     True
Name: Ranking, dtype: bool

high = global_output.loc[~mask, 'Word'].tolist()
low = global_output.loc[mask, 'Word'].tolist()

print (high)
['shuttle', 'flying', 'flight', 'trip']

print (low)
['transport', 'escape', 'trajectory', 'departure', 'arrival']

您的解决方案也有效,只需按Series将一个项目scalar转换为item(),似乎>必须为<

split = global_output['Ranking'].quantile([0.5])
print (split)
0.5    0.625
Name: Ranking, dtype: float64

split = global_output['Ranking'].quantile([0.5]).item()
print (split)
0.625

您得到error因为您比较了一个项目Series