首页 > 解决方案 > 如何从 Pandas DataFrame 的特定列中提取包含特定字符串的所有行号?

问题描述

我想可视化我从带有熊猫的 CSV 文件创建的用于学校作业的 DataFrame。DataFrame 包含有关来自两个不同书籍章节的句子的数据。我想从一个特定的书章中提取数据并创建两个新的单独的 DataFrame。因此,我试图访问“章节”列中包含“1”(如第 1 章)的所有行。这是数据框的样子:

    length                                          sentences  chapter  ranking
0       99  The word "house" is not a linguistic fact if b...        1        1
1      201  In an age when the study of antiquity attracte...        2        1
2       88  This can only mean that the sounds of speech a...        1        2
3      145  If you consider that whatever view we take of ...        2        2
4       75  If the involuntary cry of pain which is conven...        1        3
5      136  For it is evident we observe no footsteps in t...        2        3
6       71  The auditory centers alone may be excited; or ...        1        4
7      118  Man had studied every part of nature the miner...        2        4
8       68  The auditory symbolism may be replaced point f...        1        5
9      116  It has absorbed the thoughts of men who after ...        2        5
10      68  These symbols are in the first instance audito...        1        6
11      93  The dimensions of the science of language are ...        2        6
12      68  Naturally the particular points or clusters of...        1        7
13      91  The astronomer retains these and many other na...        2        7
14      66  It is even conceivable if not exactly likely t...        1        8
15      92  Lord Monboddo for instance admits that as yet ...        2        8
16      65  As such they may be considered an integral por...        1        9
17      89  It is counted as a science by so sound and sob...        2        9
18      63  If language can be said to be definitely "loca...        1       10
19      86  If with all these difficulties and drawbacks I...        2       10

我尝试使用此代码选择想要的行并将它们分配给一个新变量(第 1 章):

df = pd.read_csv('task1.csv')

chapter1 = df[df.chapter == '1']

我想为这些行创建一个新的数据框。我收到错误消息:元素比较失败;而是返回标量,但将来将执行元素比较

我该如何解决这个错误?

感谢所有帮助

标签: pythonpandasplotly-dash

解决方案


推荐阅读