如果另一列的值符合某些条件,我想打印一列的值。在下面的示例中,如果学生的分数为 5,我想打印学生的姓名。(为简单起见,数据框中只有一个学生。
df = pd.DataFrame()
df['name'] = ['jane']
df['score'] = [5]
当我尝试使用最简单的解决方案打印名称时,除了名称之外,我得到了一堆东西:
In [62]:
print(df['name'][df['score'] == 5])
0 jane
Name: name, dtype: object
当我尝试使用 .to_string 函数时,我仍然得到索引号:
In [60]:
print(df['name'][df['score'] == 5].to_string())
Out[60]:
[0 jane
Name: name, dtype: object]
最后,我查看了 .to_string() documentation并发现了这个:
index : bool, optional whether to print index (row) labels, default True
但是,当我尝试使用 .to_string(index=False) 时,出现错误:
In [64]:
df['name'][df['score'] == 5].to_string(index = False)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-54-4ed8cfe4b098> in <module>()
----> 6 df['name'][df['score'] == 5].to_string(index = False)
TypeError: to_string() got an unexpected keyword argument 'index'
请您参考如下方法:
您链接到的文档是针对 DataFrame.to_string 的,但您在系列上调用 to_string(因为您首先使用 df[ 选择一列'名称'])。 The documentation Series.to_string 表明它不接受 index 参数。
有人可能会争辩说也许它应该有一个,但行为至少与文档一致。
