且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pandas :合并multiIndex DataFrame的标题行

更新时间:2023-12-06 12:54:22

1.使用Python 3.6及更高版本进行更新,将 f字符串格式与列表一起使用理解力:

1. Update using Python 3.6+ use f-string formatting with list comprehension:

df.columns = [f'{i}{j}' for i, j in df.columns]

2.使用mapjoin:

2. Use map and join:

df.columns = df.columns.map(''.join)

3.如果您的列具有数字数据类型,请使用mapformat:

3. If your columns has numeric datatypes, use map and 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