如何快速将行插入数据帧?



我想将数据插入到数据帧的第一行,并从数据帧中删除最后一行。我需要做很多次此操作。

从这两个问题。Q1Q2 我有一些这样的代码:

targetDF = pd.concat([sourceDF[sourceDF.index == targetDate], targetDF[:]])
targetDF.drop(targetDF.tail(1).index, inplace = True)

这将从:

Volume     Today      Lag1      Lag2      Lag3      Lag4      Lag5  Direction
2000-05-22  23956801.0  0.338821  1.724165 -0.343514  3.191463  0.714161  0.000000        1.0
2000-05-19  50544773.0 -1.013452  0.338821  1.724165 -0.343514  3.191463  0.714161       -1.0
...                ...       ...       ...       ...       ...       ...       ...        ...
2000-01-04   3194413.0  7.397314  5.187307 -1.977310 -0.840434 -2.458993  1.666694        1.0
[100 rows x 8 columns]

自:

Volume     Today      Lag1      Lag2      Lag3      Lag4      Lag5  Direction
2000-05-23  21822575.0  1.724165 -0.343514  3.191463  0.714161  0.000000 -1.754358        1.0
2000-05-22  23956801.0  0.338821  1.724165 -0.343514  3.191463  0.714161  0.000000        1.0
...                ...       ...       ...       ...       ...       ...       ...        ...
2000-01-05   6058531.0  5.187307 -1.977310 -0.840434 -2.458993  1.666694  1.408448        1.0
[100 rows x 8 columns]

从问题1的回答来看,pd.concat()是广泛的。所以我想问一下是否有更好的方法可以做到这一点?

谢谢。

pandas.concat

修改您正在做的事情

targetDF = pd.concat([sourceDF.loc[[targetDate]], targetDF.iloc[:-1]])

pandas.DataFrame.append

或使用DataFrame方法

targetDF = sourceDF.loc[[targetDate]].append(targetDF.iloc[:-1])

请注意,在Pandas中,行的物理顺序并不那么重要 可以使用sort_indexsort_values进行更改。

另请注意,每一行都由索引标识,就像 一个数据库,它在当前数据帧中应该是唯一的

所以我的概念是:

  • 如果要添加新行,请使用append(在末尾(添加索引值比到目前为止的最大索引大 1的索引值。
  • 如果要删除行,请删除最小的行 的索引(从一开始(。

所以行的顺序与你的愿望相反,但你仍然可以 以"您的"顺序处理它们(从刚刚插入的行到 "最旧"行。

只需以与索引相反的顺序访问行。像这样:

df.loc[::-1]

最新更新