我有一个 MultiIndex Python 数据框显示如下:
我该怎么做才能提取索引名称(“index1”、“index2”)并删除数据框值上方的空行以获得这样的视图?目标是以 png 格式导出数据框。
这里是生成第一个数据框的代码:
import pandas as pd
import numpy as np
style_valeurs = {"background-color" : "white", "color" : "black", "border-color" : "black", "border-style" : "solid", "border-width" : "1px"}
style_col = [{"selector": "thead",
"props": "background-color:yellow; color :black; border:3px black;border-style: solid; border-width: 1px"
},{
'selector':"th:not(.index_name)",
'props':"background-color: yellow; border-color: black;border-style: solid ;border-width: 1px; text-align:left"
}]
data = np.random.rand(4,4)
columns = pd.MultiIndex.from_product([["A","B"],["C","D"]])
index = pd.MultiIndex.from_product([["x","y"],["1","2"]])
df = pd.DataFrame(data, columns = columns, index = index)
df.rename_axis(["index1","index2"], inplace = True)
df.style.set_properties(**style_valeurs).set_table_styles(style_col)
这是一种方法:
df = pd.DataFrame(data, columns=columns, index=index)
# Make index as simple columns and slice them in a temporary dataframe
df = df.reset_index()
tmp = df.loc[:, ["level_0", "level_1"]]
# Replace ["x", "x", "x", "x"] with ["x", "", "x", ""]
tmp["level_0"] = [
v if not i % tmp["level_0"].nunique() else "" for i, v in enumerate(tmp["level_0"])
]
# Fix headers
tmp.columns = pd.MultiIndex.from_tuples([("col_0", "index1"), ("col_1", "index2")])
tmp = tmp.rename(columns={"col_0": ""}).rename(columns={"col_1": ""})
# Add first two columns back with the others
new_df = pd.concat([tmp, df[["A", "B"]]]
# Define a helper function to color first two columns in yellow
def color(x):
y = "background-color: yellow"
df_ = pd.DataFrame("", index=x.index, columns=x.columns)
df_.iloc[:, [0, 1]] = y
return df_
# Style the new dataframe by hiding the index (0, 1, 2, ...), applying your styles,
# color in yellow the first two columns, and align their values to the left
new_df.style.hide(axis=0).set_properties(**style_valeurs).set_table_styles(
style_col
).apply(color, axis=None).set_properties(subset=[""], **{"text-align": "left"})
这里是输出(我没有使用 Jupyter notebook,所以边框不会呈现,但它应该适合你):