我有以下数据帧,
AirPressure... WindDirection
Date Location1 Location2.......Location8593 Location8594 Location8595
2010-01-01 xxx. xxx xxx xxx. xxx.
2010-01-02 xxx. xxx xxx xxx. xxx.
2010-01-03 xxx. xxx xxx xxx. xxx.
....
2010-01-01 xxx. xxx xxx xxx. xxx.
...
2020-10-10 xxx. xxx xxx xxx. xxx.
我正在努力把它变成下面的那个。
Date AirPressure-Location1 SoilMoisture-Location1.....WindDirection-Location8595
2010-01-01 xxx. xxx xxx
......
2020-10-10 xxx. xxx xxx
我运行以下命令,
frame.columns = ['-'.join(col).strip() for col in frame.columns.values]
但我得到了
Date Location1-AirPressure Location1-SoilMoisture.....Location8595-WindDirection
2010-01-01 xxx. xxx xxx
......
2020-10-10 xxx. xxx xxx
我该如何按照上面的要求翻转姓名?
您可以使用f-string
s:
frame.columns = [ f'{b}-{a}' for a, b in frame.columns]
或通过索引更改列的顺序:
frame.columns = ['-'.join(col[::-1]).strip() for col in frame.columns]
或者:
frame = frame.swaplevel(1, 0, axis=1)
frame.columns = ['-'.join(col).strip() for col in frame.columns]