【问题标题】:How to resample a dataframe with index half as time series and half as integer如何重新采样索引一半为时间序列、一半为整数的数据帧
【发布时间】:2022-09-28 14:56:13
【问题描述】:
                             close         0
2020-01-02 09:00:00+00:00  0.467291       NaN
2020-01-02 09:30:00+00:00  0.467267       NaN
2020-01-02 10:00:00+00:00  0.467729       NaN
2020-01-02 10:30:00+00:00  0.467923       NaN
2020-01-02 11:00:00+00:00  0.466707       NaN
...                             ...       ...
1500                            NaN  0.140868
1501                            NaN  0.136557
1502                            NaN  0.131828
1503                            NaN  0.128827
1504                            NaN  0.128978

考虑这个数据框。有没有办法“填充”时间序列,所以它继续时间序列?

(请注意,0 列填充了关闭列“sideways”)。

                             close        
2020-01-02 09:00:00+00:00  0.467291       
2020-01-02 09:30:00+00:00  0.467267       
2020-01-02 10:00:00+00:00  0.467729       
2020-01-02 10:30:00+00:00  0.467923       
2020-01-02 11:00:00+00:00  0.466707       
...                             ...       
2020-17-02 09:30:00+00:00  0.161267       
2020-17-02 10:00:00+00:00  0.165729       
2020-17-02 10:30:00+00:00  0.164923       
2020-17-02 11:00:00+00:00  0.163707       
  • 我会调查您处理的数据是否实际上是正确的,因为它看起来像是被错误地合并或连接/附加
  • 正确的。这是错误地导入的。你不能在不知道它是怎么变成这样的情况下修复它。找到根本原因。

标签: python pandas dataframe


【解决方案1】:

您可以将 df 拆分为 2 个数据框。

如果您在合并之前可以访问原始的 2 个数据框 - 您可以立即使用它们。

然后你可以用你想要的日期重新索引第二个数据框,并正确合并这两个数据框:

last_ts = df['close'].last_valid_index()

df1 = df.loc[ : last_ts, ['close']]
df2 = df.iloc[len(df1) : , [1]]     # 1 is the index position of column 0
df2.index = pd.date_range(start = last_ts + pd.Timedelta('30 min'), 
                          periods = len(df2),
                          freq='30 min')
df2.columns = ['close']

result = pd.concat([df1, df2])

例子:

df = pd.DataFrame([[1, np.nan],
                   [2, np.nan],
                   [np.nan, 4]],
                   index = list(pd.date_range(start='2022', periods=2, freq='30 min')) + [1],
                   columns=['close', 0])

                     close    0
2022-01-01 00:00:00    1.0  NaN
2022-01-01 00:30:00    2.0  NaN
1                      NaN  4.0

结果:

                     close
2022-01-01 00:00:00    1.0
2022-01-01 00:30:00    2.0
2022-01-01 01:00:00    4.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2017-11-26
    • 2023-01-28
    • 2018-06-30
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多