我是一名入门级 Python 用户,刚刚开始自学使用 Python 进行数据分析。这些天我正在 Kaggle 上的 Jupyter Notebook 中练习全局自杀率数据。我在格式化结果时遇到了一些问题。我想知道如何将多个列表中的结果放入格式良好的表格中?
我使用的数据集是全局自杀日期数据。对于代码的以下部分,我想检索 min_year (即 1985 年)和 max_year (即 2016 年)中的所有国家/地区信息。
所以我期望的输出是这样的:(只是一个例子)
以下是我的代码。
country_1985 = data [(data['year']==min_year)].country.unique()
country_2016 = data [(data['year']==max_year)].country.unique()
print ([country_1985],[country_2016])
结果显示如下:
但是,我不希望它们出现在列表中。我希望它以表格格式显示,如下所示:
我尝试使用 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/