在Pandas DataFrame上调用sort_values()会引发ValueError:系列的真值不明确

问题描述 投票:0回答:1

我有一个包含特朗普推文的数据框。 polarity列包含每个推文的情感值,我正在尝试通过调用trump来基于这些值对DataFrame sort_values()进行排序。

如果我写trump.sort_values('polarity'),我会得到一个ValueError说:

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

但是,如果我写trump.head().sort_values('polarity'),它将占用DataFrame的前五行,并根据它们的polarity值对它们进行排序。

我的问题是:为什么尽管能够对我的表的“头”进行排序,但为什么我仍无法对整个表进行排序?

EDIT2 :(为清楚起见,删除了不必要的信息,合并的代码/数据)

>>> trump.head() # This is the table after adding the 'polarity' column
                     time      source         text             no_punc   polarity
786204978629185536  <time>     iPhone    <unformatted str>  <formatted>   1
786201435486781440  <time>     iPhone    <unformatted str>  <formatted>   -6.9 
786189446274248704  <time>     Android   <unformatted str>  <formatted>   1.8
786054986534969344  <time>     iPhone    <unformatted str>  <formatted>   1.5
786007502639038464  <time>     iPhone    <unformatted str>  <formatted>   1.2

这是我创建polarity列的方式:

  • [创建的DataFrametidy_formatw /列numword包含每个推特中单词的索引以及单词本身(由每个推特的ID索引)。
  • 已创建的DataFrame tidy,将每个索引/单词按其ID号分组
  • [tidy_format中创建了每个唯一ID的列表
  • 使用嵌套列表推导创建一个列表,其元素为每个推特的polarity之和>
    >>> tidy_format.head()
            num  word
        786204978629185536  0   pay
        786204978629185536  1   to
        786204978629185536  2   play
        786204978629185536  3   politics
        786204978629185536  4   crookedhillary

    >>> tidy = trump['no_punc'].str.split(expand = True).stack()
    >>> tidy.head()
        786204978629185536  0               pay
                            1                to
                            2              play
                            3          politics
                            4    crookedhillary
        dtype: object

    >>> ids = list(tidy_format.index.unique())
    >>> scores = [sum([sent['polarity'][word] if word in sent['polarity'] else 0 for word in tidy[_id]]) for _id in ids]
    >>> trump['polarity'] = scores
    >>> trump['polarity'].head()
        786204978629185536      1
        786201435486781440   -6.9
        786189446274248704    1.8
        786054986534969344    1.5
        786007502639038464    1.2
        Name: polarity, dtype: object

我有一个包含特朗普推文的数据框。列的极性包含每个tweet的情感值,我试图通过调用...

python pandas dataframe twitter series
1个回答
-1
投票

[使用kwarg:trump.head().sort_values(by="polarity")对头部进行排序,或trump.sort_values(by="polarity").head()对所有内容进行排序并显示头部(最低极性)。

© www.soinside.com 2019 - 2024. All rights reserved.