我有一个包含特朗普推文的数据框。 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
列的方式:
tidy_format
w /列num
,word
包含每个推特中单词的索引以及单词本身(由每个推特的ID索引)。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的情感值,我试图通过调用...
[使用kwarg:trump.head().sort_values(by="polarity")
对头部进行排序,或trump.sort_values(by="polarity").head()
对所有内容进行排序并显示头部(最低极性)。