【问题标题】:Offset a part of a dataframe by hours按小时偏移数据帧的一部分
【发布时间】:2015-03-24 11:48:59
【问题描述】:

我有一部分测量仪器时间配置错误,这需要纠正。

所以我试图将我的数据帧的一部分偏移或移动 2 小时,但我似乎无法让它与我的以下代码一起使用:

dfs['2015-03-23 10:45:00':'2015-03-23 13:15:00'].shift(freq=datetime.timedelta(hours=2))

我不知道这是否可以轻松完成。

希望有人能理解我的问题:)


>>> dfs.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 11979 entries, 2015-03-23 10:45:05 to 2015-03-23 16:19:32
Data columns (total 11 columns):
CH-1[V]        11979 non-null float64
CH-2[V]        11979 non-null float64
CH-3[V]        11979 non-null float64
CH-4[V]        11979 non-null float64
CH-5[V]        11979 non-null float64
CH-6[V]        11979 non-null float64
CH-7[V]        11979 non-null float64
CH-9[C]        11979 non-null float64
CH-10[C]       11979 non-null float64
Event          11979 non-null int64
Unnamed: 11    0 non-null float64
dtypes: float64(10), int64(1)
memory usage: 1.1 MB

【问题讨论】:

  • 你想只增加 2 小时吗?
  • 是的,但仅限于那部分数据,我尝试了 +timedelta 的东西,但也没有用
  • 你能发df.info()吗,基本上你可以将Timedelta添加到各个列
  • dfs.info() DatetimeIndex:11979 个条目,2015-03-23 10:45:05 到 2015-03-23 16:19: 32个数据列(共11列):CH-1[V] 11979 non-null float64 CH-2[V] 11979 non-null float64 CH-3[V] 11979 non-null float64 CH-4[V] 11979 non -null float64 CH-5[V] 11979 non-null float64 CH-6[V] 11979 non-null float64 CH-9[C] 11979 non-null float64 CH-10[C] 11979 non-null float64 Event 11979 non -null int64 未命名:11 0 非空 float64 dtypes:float64(10),int64(1) 内存使用量:1.1 MB
  • 请将其编辑到问题中,而不是作为评论,谢谢

标签: python-3.x pandas


【解决方案1】:

Pandas 索引是不可变的,因此我们不能就地更改索引。 但是,我们可以将索引设为 DataFrame 列,修改该列,然后重置索引:

import numpy as np
import pandas as pd

# Suppose this is your `dfs`:
index = pd.date_range('2015-03-23 10:45:05', '2015-03-23 16:19:32', freq='T')
N = len(index)
dfs = pd.DataFrame(np.arange(N), index=index)

# move the index into a column
dfs = dfs.reset_index()
mask = (index >= '2015-03-23 10:45:00') & (index <= '2015-03-23 13:15:00')

# shift the masked values in the column
dfs.loc[mask, 'index'] += pd.Timedelta(hours=2)

# use the index column as the index
dfs = dfs.set_index(['index'])

这表明索引已经移动了 2 小时:

In [124]: dfs.iloc[np.where(mask)[0].max()-1:].head(5)
Out[124]: 
                       0
index                   
2015-03-23 15:13:05  148
2015-03-23 15:14:05  149    <-- shifted by 2 hours
2015-03-23 13:15:05  150    <-- unchanged
2015-03-23 13:16:05  151
2015-03-23 13:17:05  152

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多