首页 > 解决方案 > 时间序列在切片和相乘时返回 NaN

问题描述

片段:

import numpy as np
import pandas as pd

dr = pd.date_range(start='1984-01-01', end='1984-01-10')
df = pd.DataFrame(np.arange(len(dr)), index=dr, columns=["Values"])

df.iloc[:-5,] * df.iloc[5:,]

返回:

在此处输入图像描述

如果我不切片,则乘法有效:

df*df

返回:

在此处输入图像描述

所以我的猜测是,当索引不匹配时,Pandas 不会执行任何操作并简单地返回NaN

标签: pandastime-series

解决方案


DatatimeIndex两个 sliced 的问题都不同DataFrames,可能的解决方案是 numpy 数组的多个,以防止数据对齐不同的索引返回NaNs:

print (df.iloc[:-5,].index)
DatetimeIndex(['1984-01-01', '1984-01-02', '1984-01-03', '1984-01-04',
               '1984-01-05'],
              dtype='datetime64[ns]', freq='D')

print (df.iloc[5:,].index)
DatetimeIndex(['1984-01-06', '1984-01-07', '1984-01-08', '1984-01-09',
               '1984-01-10'],
              dtype='datetime64[ns]', freq='D')

print (df.iloc[:-5,] * df.iloc[5:,].values)
            Values
1984-01-01       0
1984-01-02       6
1984-01-03      14
1984-01-04      24
1984-01-05      36

或者在两个切片数据帧中创建相同的索引值:

print(df.iloc[5:,])
            Values
1984-01-06       5
1984-01-07       6
1984-01-08       7
1984-01-09       8
1984-01-10       9

print(df.iloc[5:,].set_index(df.index[:-5]))
            Values
1984-01-01       5
1984-01-02       6
1984-01-03       7
1984-01-04       8
1984-01-05       9

print(df.iloc[:-5,] * df.iloc[5:,].set_index(df.index[:-5]))
            Values
1984-01-01       0
1984-01-02       6
1984-01-03      14
1984-01-04      24
1984-01-05      36

下一种方法是在两个 DataFrames 中通过 numpy 数组进行多次处理,然后使用 DataFrame 构造函数:

print(pd.DataFrame(df.iloc[:-5,].values * df.iloc[5:,].values, 
                   columns=df.columns,
                   index=df.index[:-5]))
            Values
1984-01-01       0
1984-01-02       6
1984-01-03      14
1984-01-04      24
1984-01-05      36

推荐阅读