使用Python pandas获取所有数据帧行[重复]

Posted

技术标签:

【中文标题】使用Python pandas获取所有数据帧行[重复]【英文标题】:Fetching all rows of dataframe using Python pandas [duplicate] 【发布时间】:2017-12-08 17:07:54 【问题描述】:

我运行了一个 python 代码并得到如下数据帧输出:

1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)

现在我没有从 7 到 29 的行。如何获取所有行?

【问题讨论】:

【参考方案1】:

只是显示问题,我更喜欢:

#temporaly display 999 rows
with pd.option_context('display.max_rows', 999):
    print (df)

退出with 块时会自动恢复选项值。

【讨论】:

如果我不申请'with'怎么办? 我喜欢这个选项,因为不需要设置和重置选项。谢谢。 哦,明白了。只是一般性问题,为什么我们需要重置它以及为什么我们总是必须关闭我们打开的文件以继续执行下一行代码? 我认为您需要查看this 文章。有更好的解释作为我的解释。谢谢。 如何在带有滚动表的 jupyter-lab notebook 中做同样的事情?【参考方案2】:

从 0.20.2 开始,默认情况下,pandas 仅显示数据中的 60 行。你可以改变这个

pd.set_option('display.max_rows',n)

其中n 是您希望它显示的行数。

【讨论】:

简洁明了。 这并不像预期的那样工作 - 如果行数小于或等于 n,它工作正常,但如果行数大于 n,python 将恢复显示前 5 个和最后 5 个。要使其适用于任何数据框 df,您可以使用 pd.set_option('display.max_rows', df.shape[0])【参考方案3】:

你可以创建一个这样的函数

def print_full(x):
    pd.set_option('display.max_rows', len(x))
    print(x)
    pd.reset_option('display.max_rows')

【讨论】:

set_option和reset_option有什么区别? set_option 设置指定选项的值,而 reset_option 将一个或多个选项重置为其默认值。在我们的示例中,我们将 max_rows 默认值从 15 更改为数据帧的长度。所以 reset_option 只是回到默认值。 欲了解更多信息,请查看此链接set_optionreset_option 好的,明白了。但是为什么要再次设置默认值呢?

以上是关于使用Python pandas获取所有数据帧行[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Pandas 按功能过滤数据帧行

将 pandas 数据帧行移动到最近的时间步长

Pandas过滤值小于10且大于1000的数据帧行[重复]

根据字符串值列对 pandas 数据帧行进行排序

将 CountVectorizer 和 TfidfTransformer 稀疏矩阵转换为单独的 Pandas 数据帧行

将 spark 数据帧行写入 dynamoDB 表中的项目