如何使用熊猫将层次结构列合并为1列?

时间:2020-08-19 03:37:16

标签: python pandas

我有一个如下所示的Excel工作表。

enter image description here

我想使用熊猫将所有这些hierarichial列合并为如下所示的1列

enter image description here

有没有可以这样合并的方法,请告诉我怎么做?

1 个答案:

答案 0 :(得分:1)

您可以将df.bfillaxis = 1结合使用,然后使用iloc提取第一列

>>> import pandas as pd
>>> df = pd.DataFrame([[1, None, None, None], [None, 2, None, None], [None, None, 3, None], [None, None, None, 4]])
>>> df
     0    1    2    3
0  1.0  NaN  NaN  NaN
1  NaN  2.0  NaN  NaN
2  NaN  NaN  3.0  NaN
3  NaN  NaN  NaN  4.0
>>> df = df.bfill(axis=1).iloc[:, 0]
>>> df
0    1.0
1    2.0
2    3.0
3    4.0
Name: 0, dtype: float64
相关问题