使用period_range重新编制索引时,熊猫数据帧NaN

时间:2019-03-05 16:35:19

标签: pandas dataframe reindex

我希望代码添加数据框中不存在的新行。使用period_range重新索引时,我得到的是NaN值。我得到正确的period_range但为NaN,而不是保留列'A'的可用值。下面显示了代码示例:

我想问题出来了,因为使用了PeriodIndex和DatetimeIndex对象。

                      A
2018-10-31 14:08:26 NaN
2018-10-31 14:08:27 NaN
2018-10-31 14:08:28 NaN
2018-10-31 14:08:29 NaN
2018-10-31 14:08:30 NaN


import pandas as pd

data=[['2018-10-31 14:08:26', 1],
      ['2018-10-31 14:08:28', 2],
      ['2018-10-31 14:08:30', 3]]

df = pd.DataFrame(data=data, columns=['time','A'])
df.time = pd.to_datetime(df.time)
ts = df.time
idx = pd.period_range(min(ts), max(ts),freq='s')
df = df.set_index('time',drop=True)
df = df.reindex( idx )

2 个答案:

答案 0 :(得分:2)

data = [['2018-10-31 14:08:26', 1],
        ['2018-10-31 14:08:28', 2],
        ['2018-10-31 14:08:30', 3]]

df = pd.DataFrame(data=data, columns=['time','A'])
df['time'] = pd.to_datetime(df['time'])
df.set_index('time').resample('S').asfreq()

输出

>>> df
                        A
time    
2018-10-31 14:08:26     1.0
2018-10-31 14:08:27     NaN
2018-10-31 14:08:28     2.0
2018-10-31 14:08:29     NaN
2018-10-31 14:08:30     3.0

答案 1 :(得分:0)

需要将DatetimeIndex更改为PeriodIndex:

df = df.set_index('time',drop=True)
df.index=df.index.to_period('S')
df = df.reindex( idx )

                       A
2018-10-31 14:08:26  1.0
2018-10-31 14:08:27  NaN
2018-10-31 14:08:28  2.0
2018-10-31 14:08:29  NaN
2018-10-31 14:08:30  3.0