首页 > 解决方案 > 尝试从具有条件转置的源数据帧行创建一个新数据帧

问题描述

我有一个类似于下面提供的数据框:

time   count1   count2  result
t1      c11       c21     r1
t2      c12       c22     r2
t3      c13       c23     r3
t4      c14       c24     r4
t5      c15       c25     r5
t6      c16       c26     r6

我想准备一个如下所示的数据框:

df1    
count1-1   count1-2  count1-3  count2-1  count2-2  count2-3  result 
    c11       c12      c13        c21       c22       c23      r4       
    c14       c15      c16        c24       c25       c26      r5      

请注意,结果列的偏移量为 +1。所以计数是 3 行,相应的结果是下一行,即第 4 行。

我有一个代码可以接受值之间的差异,但我不想接受差异。我的代码如下所示。我知道有一个小的变化,但是我很困惑如何改变逻辑。

df1 = pd.concat([-df['count1'].diff(periods=-i) for i in range(1, lag + 1)], axis=1).dropna(axis=0)
df2 = pd.concat([-df['count2'].diff(periods=-i) for i in range(1, lag + 1)], axis=1).dropna(axis=0)
cdf = pd.concat([df1,df2], axis=1)

target_df = df.copy(deep=True)
target_df = df.iloc[:len(df1)]
target_df = target_df.drop(columns=['count1', 'count2'])

标签: python-3.xpandastime-series

解决方案


推荐阅读