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

我有一个包含6行和3列的数据表。


a b c 

d e f

g h i 

j k l

m 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 l

g h i j k l m n o

j k l m n o p q r

我该怎么做?感谢您的帮助。!!


qq_花开花谢_0
浏览 90回答 2
2回答

有只小跳蛙

您可以通过1行代码来实现这一点。这是一个例子import pandas as pda = 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)不要忘记重命名索引和列。

慕虎7371278

您可以通过numpy.ravel使用具有扁平值的步幅,最后通过索引选择每行:3thdef 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  80  a  b  c  d  e  f  g  h  i1  d  e  f  g  h  i  j  k  l2  g  h  i  j  k  l  m  n  o3  j  k  l  m  n  o  p  q  r一般解决方案:N = 3M = len(df.columns)a = rolling_window(df.to_numpy().ravel(), M*N)[::M]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python