【问题标题】:How to generate a new Pandas dataframe where I compress some rows into a new column?如何生成一个新的 Pandas 数据框,将一些行压缩到一个新列中?
【发布时间】:2018-01-28 13:10:09
【问题描述】:

我对 pandas DataFrame 相当陌生,但我一直在观看教程和阅读有关它的文档,但我无法完全找到一种方法来做我想做的事。我有一个按时间戳索引的 DataFrame,我想将某个时间段存储到一行中。图形化:

    # start date of the series
start_date='20130101'
# range of dates
dates = pd.date_range(start_date, periods=6)

# random dataframe
df = pd.DataFrame([["(1,1)","(1,2)"],
                   ["(2,1)","(2,2)"],
                   ["(3,1)","(3,2)"],
                   ["(4,1)","(4,2)"],
                   ["(5,1)","(5,2)"],
                   ["(6,1)","(6,2)"]], index=dates, columns=list('AB'))
print(df)
# range of bucketing periods, in this case I will get just three periods covering two days each
rng = pd.period_range(start_date, periods=3,freq='2D')

这会导致

              A      B
2013-01-01  (1,1)  (1,2)
2013-01-02  (2,1)  (2,2)
2013-01-03  (3,1)  (3,2)
2013-01-04  (4,1)  (4,2)
2013-01-05  (5,1)  (5,2)
2013-01-06  (6,1)  (6,2)

我现在想做的是生成一个新的数据框,其中我将rng = pd.period_range(start_date, periods=3,freq='2D') 中的句点作为索引,并将与该句点对应的行作为连续列:

              A      B      A1      B1
2013-01-01  (1,1)  (1,2)  (2,1)  (2,2)            
2013-01-03  (3,1)  (3,2)  (4,1)  (4,2)  
2013-01-05  (5,1)  (5,2)  (6,1)  (6,2)

我可以使用 Api 中的任何方法来执行此操作吗? 我想我还需要生成 A1、B1 等新标签。

另外,经过我的思考,我可能会这样做

              A      A1      B      B1
2013-01-01  (1,1)  (2,1)  (1,2)  (2,2)            
2013-01-03  (3,1)  (4,1)  (3,2)  (4,2)  
2013-01-05  (5,1)  (6,1)  (5,2)  (6,2)

【问题讨论】:

  • 周期是如何决定的?
  • 周期来自上述定义的周期范围 rng。对于这个例子,我将其作为 2d 周期。
  • 我问是因为你想要的可以通过简单的重塑来实现:pd.DataFrame(np.reshape(df.values, (-1, 4)))
  • 这是一种方法,谢谢。但是,我想根据时间戳和我生成的周期进行选择。

标签: python pandas dataframe time-series


【解决方案1】:

其中一种方法是将句点转换为timestamp 并制作一个数据框,然后使用ffill 方法将它们填充NaN,并将reshape based on index 设置为新的时间戳列作为索引,即

n = pd.DataFrame(rng.to_timestamp()).set_index(rng.to_timestamp())

result = pd.concat([df, n], axis=1).fillna(method='ffill').set_index(0)

result = result.set_index(result.groupby(level=0).cumcount(), append=True).unstack()

输出

甲乙 0 1 0 1 0 2013-01-01 (1,1) (2,1) (1,2) (2,2) 2013-01-03 (3,1) (4,1) (3,2) (4,2) 2013-01-05 (5,1) (6,1) (5,2) (6,2) 在 [1024] 中:

【讨论】:

  • 这正是我想要的。非常感谢。
  • 很高兴帮助@Paco
猜你喜欢
  • 2016-03-22
  • 2019-06-09
  • 1970-01-01
  • 2019-07-26
  • 2021-02-27
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 2019-04-16
相关资源
最近更新 更多