pandas - 时间序列在切片和相乘时返回 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
?
解决方案
DatatimeIndex
两个 sliced 的问题都不同DataFrames
,可能的解决方案是 numpy 数组的多个,以防止数据对齐不同的索引返回NaN
s:
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
推荐阅读
- c# - C# 与 Word 通配符互操作:如何在 Find 中包含可选空间?
- javascript - 如何检查元素的孩子是否也包含孩子
- tsql - 账单日期的平均月份范围
- selenium-webdriver - 端口 4444 正忙,请选择一个空闲端口并使用 -port 选项指定它
- python - 尝试在 Python 中对 NI USB-6009 设备进行编程,但由于错误 -200077 无法修复模拟输出电压
- ruby-on-rails - 使用 Google Calendar API 在 Rails 应用程序中处理时区
- java - Firebase Android在长按的ListView中删除节点键
- python - Pandas 重采样:TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但获得了“RangeIndex”实例
- c# - 泛型类中的属性。在 Find of Mongodb 中获取属性
- javascript - setInterval() 中的 .load 调用只能工作一次