删除NaN单元格并根据Datetime索引移动非空值

时间:2015-09-03 14:23:22

标签: python python-3.x pandas

我有这样的DataFrame

                     a     b      c       d
2014-02-10 23:30:00 25.1  NaN    NaN     NaN
2014-02-10 23:30:00 NaN   15.34  NaN     NaN
2014-02-10 23:30:00 NaN   NaN    123.54  NaN
2014-02-10 23:30:00 NaN   NaN    NaN     1.34

其中一次性步骤我有4个值 - 每列一个值。所有其他都是NaN

是否可以删除NaN值并且每一步只留下4个值?有这样的事情:

                     a     b      c       d
2014-02-10 23:30:00 25.1  15.34  123.54  1.34

我尝试过应用@unutbu提供的Remove NaN 'Cells' 解决方案,但没有取得任何成功:

import numpy as np
import pandas as pd
import functools

def drop_and_roll(col, na_position='last', fillvalue=np.nan):
    result = np.full(len(col), fillvalue, dtype=col.dtype)
    mask = col.notnull()
    N = mask.sum()
    if na_position == 'last':
        result[:N] = col.loc[mask]
    elif na_position == 'first':
        result[-N:] = col.loc[mask]
    else:
        raise ValueError('na_position {!r} unrecognized'.format(na_position))
    return result

df = pd.read_table('data', sep='\s{2,}')

print(df.apply(functools.partial(drop_and_roll, fillvalue='')))

1 个答案:

答案 0 :(得分:2)

您只需groupby索引并致电sum

In [70]:
df.groupby(df.index).sum()

Out[70]:
                        a      b       c     d
2014-02-10 23:30:00  25.1  15.34  123.54  1.34