考虑以下数据框:
{('CA', 'ca'): {('A', 'a'): 2,
('A', 'aa'): 2,
('B', 'b'): 2,
('B', 'bb'): 2,
('C', 'c'): 2,
('C', 'cc'): 2},
('CA', 'cb'): {('A', 'a'): 1,
('A', 'aa'): 1,
('B', 'b'): 1,
('B', 'bb'): 1,
('C', 'c'): 1,
('C', 'cc'): 1}}
如何将数据框转换为可通过复制和粘贴类似于此布局的方法插入布局字符串中?
+-------------+----------+---------+
| First | Second | Third |
+=============+==========+=========+
| ('A', 'a') | 2 | 1 |
+-------------+----------+---------+
...
答案 0 :(得分:2)
tabulate
可能会让您入门:
import pandas as pd
from tabulate import tabulate
df = pd.DataFrame(
{
("CA", "ca"): {
("A", "a"): 2,
("A", "aa"): 2,
("B", "b"): 2,
("B", "bb"): 2,
("C", "c"): 2,
("C", "cc"): 2,
},
("CA", "cb"): {
("A", "a"): 1,
("A", "aa"): 1,
("B", "b"): 1,
("B", "bb"): 1,
("C", "c"): 1,
("C", "cc"): 1,
},
}
)
tab = tabulate(df, tablefmt="grid")
print(tab)
输出
+-------------+---+---+
| ('A', 'a') | 2 | 1 |
+-------------+---+---+
| ('A', 'aa') | 2 | 1 |
+-------------+---+---+
| ('B', 'b') | 2 | 1 |
+-------------+---+---+
| ('B', 'bb') | 2 | 1 |
+-------------+---+---+
| ('C', 'c') | 2 | 1 |
+-------------+---+---+
| ('C', 'cc') | 2 | 1 |
+-------------+---+---+
您还可以添加headers
:
headers = ["First", "Second", "Third"]
tab = tabulate(df, headers=headers, tablefmt="grid")
然后会生成
+-------------+----------+---------+
| First | Second | Third |
+=============+==========+=========+
| ('A', 'a') | 2 | 1 |
+-------------+----------+---------+
...