为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 python 中追加行中最近的行

如何在 python 中追加行中最近的行

qq_花开花谢_0 2022-09-06 15:45:59
我有一个包含6行和3列的数据表。a b c d e fg h i j k lm n o p q r我想在每行中追加最接近的2行。将追加 1 个上行和下行 1 个。a b c d e f g h i d e f g h i j k lg h i j k l m n oj k l m n o p q r我该怎么做?感谢您的帮助。!!
查看完整描述

2 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

您可以通过1行代码来实现这一点。这是一个例子


import pandas as pd

a = pd.DataFrame([

    ['a', 'b', 'c'],

    ['d', 'e', 'f'],

    ['g', 'h', 'i'],

    ['j', 'k', 'l'],

    ['m', 'n', 'o'],

    ['p', 'q', 'r']

])

现在将数据帧移动 1 行并连接它们


a_1 = a.shift(-1)

a_2 = a.shift(-2)

c = pd.concat([a, a_1, a_2], axis=1)

然后更正新数据帧中的行


c = c.iloc[:-2]

完整代码如下


a = pd.DataFrame([

    ['a', 'b', 'c'],

    ['d', 'e', 'f'],

    ['g', 'h', 'i'],

    ['j', 'k', 'l'],

    ['m', 'n', 'o'],

    ['p', 'q', 'r']

])

b = pd.concat([a, a.shift(-1), a.shift(-2)], axis=1).iloc[:-2]

print(a)

print(b)

不要忘记重命名索引和列。


查看完整回答
反对 回复 2022-09-06
?
慕虎7371278

TA贡献1802条经验 获得超4个赞

您可以通过numpy.ravel使用具有扁平值的步幅,最后通过索引选择每行:3th

def rolling_window(a, window):

    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)

    strides = a.strides + (a.strides[-1],)

    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)


a = rolling_window(df.to_numpy().ravel(), 9)[::3]

print (a)

[['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i']

 ['d' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l']

 ['g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o']

 ['j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r']]


df = pd.DataFrame(a)

print (df)

   0  1  2  3  4  5  6  7  8

0  a  b  c  d  e  f  g  h  i

1  d  e  f  g  h  i  j  k  l

2  g  h  i  j  k  l  m  n  o

3  j  k  l  m  n  o  p  q  r

一般解决方案:


N = 3

M = len(df.columns)

a = rolling_window(df.to_numpy().ravel(), M*N)[::M]


查看完整回答
反对 回复 2022-09-06
  • 2 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号