I am trying to create a dataframe that looks similar to an excel file, something like this:
The code I am using right now:
1) Import packages
JavaScript
x
41
41
1
import os
2
import numpy as np
3
import pandas as pd
4
import matplotlib.pyplot as plt
5
import math
6
from IPython.core.interactiveshell import InteractiveShell
7
InteractiveShell.ast_node_interactivity = "all"
8
9
10
# 2) Define functions
11
12
def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
13
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
14
bbox=[0, 0, 1, 1], header_columns=0,
15
ax=None, **kwargs):
16
if ax is None:
17
size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
18
fig, ax = plt.subplots(figsize=size)
19
ax.axis('off')
20
mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)
21
mpl_table.auto_set_font_size(False)
22
mpl_table.set_fontsize(font_size)
23
24
for k, cell in mpl_table._cells.items():
25
cell.set_edgecolor(edge_color)
26
if k[0] == 0 or k[1] < header_columns:
27
cell.set_text_props(weight='bold', color='w')
28
cell.set_facecolor(header_color)
29
else:
30
cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
31
return ax.get_figure(), ax
32
33
df = pd.DataFrame()
34
df['Planet'] = ['Earth','Mercury', 'Jupiter']
35
df['time'] = [2200, 2100, 1500]
36
df['distance'] = [8, 7.5, 8.2]
37
df['Bz'] = [9,8, 10]
38
39
40
fig,ax = render_mpl_table(df, header_columns=0, col_width=2.0)
41
What I am getting:
What I want to do is have the dataframe show the index vertically, using the same index for 3 consequent rows at a time.
Advertisement
Answer
How about this? I added column R(km)
as the expected output you showed but you can
apply the same principle for other column as the second index.
JavaScript
1
8
1
df = pd.DataFrame()
2
df['Planet'] = ['Earth']*3 + ['Mercury']*3 +['Jupiter']*3
3
df['R(km)'] = [100]*3 + [200]*3 +[300]*3
4
df['time'] = [2200, 2100, 1500]*3
5
df['distance'] = [8, 7.5, 8.2]*3
6
df['Bz'] = [9,8, 10]*3
7
df.set_index(['Planet', 'R(km)'])
8