Pandas:合并多索引数据帧的 header 行
Pandas: combining header rows of a multiIndex DataFrame
假设我有一个 DataFrame 如下:
first bar baz foo
second one two one two one two three
A 1 2 3 4 5 6 7
B 8 9 10 11 12 13 14
我想像这样创建一个新的 DataFrame:
barone bartwo bazone baztwo fooone footwo foothree
A 1 2 3 4 5 6 7
B 8 9 10 11 12 13 14
可能的代码是什么?
1。使用 Python 更新 3.6+ 使用 f-string formatting 和列表理解:
df.columns = [f'{i}{j}' for i, j in df.columns]
2。使用 map
和 join
:
df.columns = df.columns.map(''.join)
3。如果您的列具有数字数据类型,请使用 map
和 format
:
df.columns = df.columns.map('{0[0]}{0[1]}'.format)
输出:
barone bartwo bazone baztwo fooone footwo foothree
A 1 2 3 4 5 6 7
B 8 9 10 11 12 13 14
假设我有一个 DataFrame 如下:
first bar baz foo
second one two one two one two three
A 1 2 3 4 5 6 7
B 8 9 10 11 12 13 14
我想像这样创建一个新的 DataFrame:
barone bartwo bazone baztwo fooone footwo foothree
A 1 2 3 4 5 6 7
B 8 9 10 11 12 13 14
可能的代码是什么?
1。使用 Python 更新 3.6+ 使用 f-string formatting 和列表理解:
df.columns = [f'{i}{j}' for i, j in df.columns]
2。使用 map
和 join
:
df.columns = df.columns.map(''.join)
3。如果您的列具有数字数据类型,请使用 map
和 format
:
df.columns = df.columns.map('{0[0]}{0[1]}'.format)
输出:
barone bartwo bazone baztwo fooone footwo foothree
A 1 2 3 4 5 6 7
B 8 9 10 11 12 13 14