我是 python 的新手,正在为 pandas 中的 shift 苦苦挣扎。
我正在比较数据,但需要对齐才能进行比较。要对齐数据,我只需要移动其中一个数据的索引值。
Reference data: Data to be shifted:
acc acc
index index
1480681219**96**0000000 1 1480681220**04**0000000 8
1480681220**00**0000000 2 1480681220**08**0000000 9
1480681220**04**0000000 3 1480681220**12**0000000 7
1480681220**08**0000000 4 1480681220**16**0000000 10
1480681220**12**0000000 5 1480681220**20**0000000 6
(粗体编辑选项似乎不起作用,但我想突出显示索引的那些部分)
我想在给定额外时间的情况下移动我的数据框。请注意,时间以纳秒为单位。我意识到像 df.shift(2) 这样的东西将我的数据移动了 2 个位置,但我想用 -80000000 纳秒移动我的数据,在这种情况下是 2 个位置:
输入:
acc
index
1480681220040000000 8
1480681220080000000 9
1480681220120000000 7
1480681220160000000 10
1480681220200000000 6
期望的输出:
acc
index
1480681219960000000 8
1480681220000000000 9
1480681220040000000 7
1480681220080000000 10
1480681220120000000 6
1480681220160000000 NaN
1480681220200000000 NaN
这是我的代码的较小规模:
class device_data(object):
def __init__(self):
_index = [1480681220040000000,
1480681220080000000,
1480681220120000000,
1480681220160000000,
1480681220200000000]
self.df = pd.DataFrame({'acc': [8, 9, 7, 10, 6], 'index': _index})
self.df = self.df.set_index('index')
if __name__ == '__main__':
extratime = np.int64(-40000000)
session = dict()
session[2] = {'testnumber': '401',
'devicename': 'peanut'}
session[2]['data_in_device_class'] = device_data()
print session[2]['data_in_device_class'].df
if hasattr(session[2]['data_in_device_class'], 'df'):
session[2]['data_in_device_class'].df = session[2]['data_in_device_class'].df.shift(int(round(extratime)))
else:
pass
print session[2]['data_in_device_class'].df
当我运行原始代码时,它给了我这个错误:OverflowError: Python int too large to convert to C long
我使用 extratime = np.int64(extratime) 来解决这个问题。我注意到,对于我的代码的缩小版本,它并不是真正需要的。
我的问题仍然是如何使用 shift 来移动我的索引,而不是它需要移动的位置数量?
谢谢
请您参考如下方法:
首先你想将你的索引移动所需的量,然后是reindex,为了让事情更简单,我在这里复制一个copy,移动索引,然后我们reindex 在移位索引和原始索引的 union 上引入 NaN 行:
In [232]:
df1 = df.copy()
df1.index -= 80000000
df1.reindex(df1.index.union(df.index))
Out[232]:
acc
index
1480681219960000000 8.0
1480681220000000000 9.0
1480681220040000000 7.0
1480681220080000000 10.0
1480681220120000000 6.0
1480681220160000000 NaN
1480681220200000000 NaN
