熊猫:用合并的单元格读取Excel

iay*_*ork 22 python excel pandas

我有多个工作表的Excel文件,每个工作表看起来都像这样(但更长):

        Sample  CD4     CD8
Day 1   8311    17.3    6.44
        8312    13.6    3.50
        8321    19.8    5.88
        8322    13.5    4.09
Day 2   8311    16.0    4.92
        8312    5.67    2.28
        8321    13.0    4.34
        8322    10.6    1.95
Run Code Online (Sandbox Code Playgroud)

第一列实际上是垂直合并的四个单元格.

当我使用pandas.read_excel读取它时,我得到一个如下所示的DataFrame:

       Sample    CD4   CD8
Day 1    8311  17.30  6.44
NaN      8312  13.60  3.50
NaN      8321  19.80  5.88
NaN      8322  13.50  4.09
Day 2    8311  16.00  4.92
NaN      8312   5.67  2.28
NaN      8321  13.00  4.34
NaN      8322  10.60  1.95
Run Code Online (Sandbox Code Playgroud)

我怎样才能让Pandas了解合并的单元格,或者通过适当的值快速轻松地删除NaN和组?(一种方法是重置索引,逐步查找值并用值替换NaN,传入日期列表,然后将索引设置为列.但似乎应该有一个更简单的方法.)

unu*_*tbu 34

您可以使用Series.fillna方法来填充NaN值:

df.index = pd.Series(df.index).fillna(method='ffill')
Run Code Online (Sandbox Code Playgroud)

例如,

In [42]: df
Out[42]: 
       Sample    CD4   CD8
Day 1    8311  17.30  6.44
NaN      8312  13.60  3.50
NaN      8321  19.80  5.88
NaN      8322  13.50  4.09
Day 2    8311  16.00  4.92
NaN      8312   5.67  2.28
NaN      8321  13.00  4.34
NaN      8322  10.60  1.95

[8 rows x 3 columns]

In [43]: df.index = pd.Series(df.index).fillna(method='ffill')

In [44]: df
Out[44]: 
       Sample    CD4   CD8
Day 1    8311  17.30  6.44
Day 1    8312  13.60  3.50
Day 1    8321  19.80  5.88
Day 1    8322  13.50  4.09
Day 2    8311  16.00  4.92
Day 2    8312   5.67  2.28
Day 2    8321  13.00  4.34
Day 2    8322  10.60  1.95

[8 rows x 3 columns]
Run Code Online (Sandbox Code Playgroud)

  • @SamarthBharadwaj:[`fillna`方法](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html)有一个`axis`参数,用于控制要填充的方向.要逐行填充DataFrame中的所有NaN,可以使用`df = df.fillna(method ='ffill',axis = 1)`.要仅填充选定的行,请使用`df.loc`或`df.iloc`.例如,`df.loc [mask] = df.loc [mask] .fillna(method ='ffill',axis = 1)`. (3认同)
  • 只要合并单元格后没有自愿空的单元格,则可以使用带有fill的fillna。 (3认同)

Nat*_*yle 15

8年后随意回来,pandas.read_excel()可以通过index_col参数在内部为您解决这个问题。

df = pd.read_excel('path_to_file.xlsx', index_col=[0])
Run Code Online (Sandbox Code Playgroud)

将index_col作为列表传递将导致pandas寻找MultiIndex。在存在长度为 1 的列表的情况下,pandas 会创建一个常规索引来填充数据。


小智 9

df = df.fillna(method='ffill', axis=0)  # resolved updating the missing row entries
Run Code Online (Sandbox Code Playgroud)

  • Stack Overflow 上通常不赞成仅使用代码的答案。为了避免被视为“低质量”而关闭,请添加一些解释性文字。 (2认同)