您还可以使用列表推导:
df.columns = ['_'.join(col) for col in df.columns]
print (df)
Winners_2016 Winners_2015 Winners_2014 Runnerup_2016 \
Country Sport
india badminton 1 1 1 1
wrestling 1 1 1 1
Runnerup_2015 Runnerup_2014
Country Sport
india badminton 1 1
wrestling 1 1
columns
to_series
转换然后调用的另一种解决方案join
:
df.columns = df.columns.to_series().str.join('_')
print (df)
Winners_2016 Winners_2015 Winners_2014 Runnerup_2016 \
Country Sport
india badminton 1 1 1 1
wrestling 1 1 1 1
Runnerup_2015 Runnerup_2014
Country Sport
india badminton 1 1
wrestling 1 1
我对时间很感兴趣:
In [45]: %timeit ['_'.join(col) for col in df.columns]
The slowest run took 7.82 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.05 µs per loop
In [44]: %timeit ['{}_{}'.format(x,y) for x,y in zip(df.columns.get_level_values(0),df.columns.get_level_values(1))]
The slowest run took 4.56 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 131 µs per loop
In [46]: %timeit df.columns.to_series().str.join('_')
The slowest run took 4.31 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 452 µs per loop