python - 对于分类数据,如何在表格而不是列表中显示结果? (Jupyter 笔记本/Python)

标签 python jupyter-notebook

我是一名入门级 Python 用户,刚刚开始自学使用 Python 进行数据分析。这些天我正在 Kaggle 上的 Jupyter Notebook 中练习全局自杀率数据。我在格式化结果时遇到了一些问题。我想知道如何将多个列表中的结果放入格式良好的表格中?

我使用的数据集是全局自杀日期数据。对于代码的以下部分,我想检索 min_year (即 1985 年)和 max_year (即 2016 年)中的所有国家/地区信息。

所以我期望的输出是这样的:(只是一个例子)

Expected Output

以下是我的代码。

country_1985 = data [(data['year']==min_year)].country.unique()
country_2016 = data [(data['year']==max_year)].country.unique()

print ([country_1985],[country_2016])

结果显示如下:

Result

但是,我不希望它们出现在列表中。我希望它以表格格式显示,如下所示: Result

我尝试使用 pandas.DataFrame,也没有任何意义...有人可以帮助我解决我的问题吗?

更新:

感谢@Code Pope 代码!!!感谢您的解释和耐心!

import pandas as pd
import numpy as np


country_1985 = data [(data['year']==min_year)].country.unique()
country_2016 = data [(data['year']==max_year)].country.unique()

country_1985 = pd.DataFrame(country_1985.categories)
country_2016 = pd.DataFrame(country_2016.categories)

# Following are the code from @Code Pope

from IPython.display import display_html
def display_side_by_side(dataframe1, dataframe2):
modified_HTML=dataframe1.to_html() + dataframe2.to_html()
display_html(modified_HTML.replace('table','table 
style="display:inline"'),raw=True)

display_side_by_side(country_1985,country_2016 )

然后它看起来像这样: Updated Output

最佳答案

正如您所说,您正在使用 Jupyter Notebook,您可以在显示数据帧之前更改其 html。使用以下函数:

from IPython.display import display_html
def display_side_by_side(dataframe1, dataframe2):
    modified_HTML=dataframe1.to_html() + dataframe2.to_html()
    display_html(modified_HTML.replace('table','table style="display:inline"'),raw=True)

# then call the function with your two dataframes
display_side_by_side(country_1985,country_2016 )

关于python - 对于分类数据,如何在表格而不是列表中显示结果? (Jupyter 笔记本/Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421827/

相关文章:

具有枚举列表的 Python(递归?)函数正在遍历未知数据

python - 具有不同颜色条的子图

jupyter-notebook - 在 Fedora 上运行 Jupyter 笔记本

python - 无需代码即可将笔记本导出为 pdf

python - 如何在 Google Colaboratory 中导入和读取一个 shelve 或 Numpy 文件?

python - 在 python 上,如何确定单击了哪个按钮

python - 如何将字符串转换为函数的参数?

python - 错误的指数幂图 - 如何改进曲线拟合

python - 在 Jupyter Notebook 中找不到 OpenCV,但在终端中找到

python-2.7 - 如何使用纬度和经度在 jupyter 笔记本中创建谷歌地图