英文:
Multi-line and spanned rows with pandas
问题
找到了解决多行标头问题的方法。
import pandas
headers = [
('data1', 'value1'),
('data1', 'value2'),
('data2', 'value1'),
('data2', 'value2'),
('data3', 'value1'),
('data3', 'value2'),
('data4', 'value1'),
('data4', 'value2'),
]
data = [
(1, 2, 3, 4, 5, 6, 7, 8),
(11, 12, 13, 14, 15, 16, 17, 18),
]
df = pandas.DataFrame(data, columns=pandas.MultiIndex.from_tuples(headers))
我不明白如何添加多行标头。
我尝试转置并添加新的多行标头 - 但什么都没有发生。有没有人有解决方案?
英文:
found a solution for a problem with multi-line headers.
import pandas
headers = [
('data1', 'value1'),
('data1', 'value2'),
('data2', 'value1'),
('data2', 'value2'),
('data3', 'value1'),
('data3', 'value2'),
('data4', 'value1'),
('data4', 'value2'),
]
data = [
(1, 2, 3, 4, 5, 6, 7, 8),
(11, 12, 13, 14, 15, 16, 17, 18),
]
df = pandas.DataFrame(data, columns=pandas.MultiIndex.from_tuples(headers))
I don't understand how to add multilines
I tried to transpose and add new multi-line headers - nothing happened. does anyone have a solution?
答案1
得分: 1
你可以像处理列一样创建水平多级索引,但使用pd.DataFrame
的index
参数:
import pandas
headers = [
('data1', 'value1'),
('data1', 'value2'),
('data2', 'value1'),
('data2', 'value2'),
('data3', 'value1'),
('data3', 'value2'),
('data4', 'value1'),
('data4', 'value2'),
]
index = [
('key1', 'val1'),
('key1', 'val2')
]
data = [
(1, 2, 3, 4, 5, 6, 7, 8),
(11, 12, 13, 14, 15, 16, 17, 18),
]
df = pandas.DataFrame(
data,
columns=pandas.MultiIndex.from_tuples(headers),
index=pandas.MultiIndex.from_tuples(index)
)
df
输出:
data1 data2 data3 data4
value1 value2 value1 value2 value1 value2 value1 value2
key1 val1 1 2 3 4 5 6 7 8
val2 11 12 13 14 15 16 17 18
英文:
You can create horizontal multiindex the same way as columns, but using index
argument of pd.DataFrame
:
import pandas
headers = [
('data1', 'value1'),
('data1', 'value2'),
('data2', 'value1'),
('data2', 'value2'),
('data3', 'value1'),
('data3', 'value2'),
('data4', 'value1'),
('data4', 'value2'),
]
index = [
('key1', 'val1'),
('key1', 'val2')
]
data = [
(1, 2, 3, 4, 5, 6, 7, 8),
(11, 12, 13, 14, 15, 16, 17, 18),
]
df = pandas.DataFrame(
data,
columns=pandas.MultiIndex.from_tuples(headers),
index=pandas.MultiIndex.from_tuples(index)
)
df
Output:
data1 data2 data3 data4
value1 value2 value1 value2 value1 value2 value1 value2
key1 val1 1 2 3 4 5 6 7 8
val2 11 12 13 14 15 16 17 18
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论