我有一个来自 excel 文件的 pandas DataFrame,其标题分为多行,如下例所示:
0 1 2 3 4 5 6 7
5 NaN NaN NaN NaN NaN NaN NaN Above
6 Planting Harvest NaN Flowering Maturity Maturity Maturity ground
7 date date Yield date date date date biomass
8 YYYY.DDD YYYY.DDD(kg/ha) YYYY.DDD YYYY.DDD YYYY.DDD YYYY.DDD (kg/ha)
9 NaN NaN NaN NaN NaN NaN NaN NaN
10 1999.26 2000.21 5669.46 2000.14 2000.19 2000.19 2000.19 11626.7
11 2000.27 2001.22 10282.5 2001.15 2001.2 2001.2 2001.2 20565
12 2001.27 2002.22 8210.09 2002.15 2002.2 2002.2 2002.2 16509
我需要按列合并(即用空白作为胶水连接)第 5 行到第 9 行(包括在内),以便只有一个这样的标题(我已经格式化表格以便于阅读,所以有标签比实际应该多)
Planting date YYYY.DDD Harvest date YYYY.DDD Yield (kg/ha) Flowering date YYYY.DDD Maturity date YYYY.DDD Maturity date YYYY.DDD Maturity date YYYY.DDD Above ground biomass (kg/ha)
1999.262 2000.206 5669.45623 2000.138 2000.19 2000.19 2000.19 11626.73122
2000.268 2001.216 10282.49713 2001.151 2001.2 2001.2 2001.2 20564.99427
2001.272 2002.217 8210.091653 2002.155 2002.201 2002.201 2002.201 16509.03802
我想这应该是微不足道的,但我找不到我的解决方案。
任何帮助将不胜感激
最佳答案
可以先通过loc
来选择,然后用 fillna
将 NaN
替换为空字符串并应用 join
。如有必要,通过 str.strip
删除第一个和最后一个空格然后通过选择 df.loc[10:]
删除第一行:
df.columns = df.loc[5:9].fillna('').apply(' '.join).str.strip()
#if need monotonic index (0,1,2...) add reset index
print (df.loc[10:].reset_index(drop=True))
Planting date YYYY.DDD Harvest date YYYY.DDD(kg/ha) Yield YYYY.DDD \
0 1999.26 2000.21 5669.46
1 2000.27 2001.22 10282.5
2 2001.27 2002.22 8210.09
Flowering date YYYY.DDD Maturity date YYYY.DDD Maturity date YYYY.DDD \
0 2000.14 2000.19 2000.19
1 2001.15 2001.2 2001.2
2 2002.15 2002.2 2002.2
Maturity date (kg/ha) Above ground biomass
0 2000.19 11626.7
1 2001.2 20565
2 2002.2 16509
关于python - 如何将 Pandas 数据框的多行标题合并到单个单元格标题中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41259735/