如何使用 pandas 将文件的前 2 行移动到末尾

How to move the first 2 rows of a file to the end with pandas

我有一个包含 2 列和 10 行的文件:

01/12/2019  234.75
02/12/2019  303.6666666666667
03/12/2019  213.29166666666663
04/12/2019  187.91666666666663
05/12/2019  191.875
06/12/2019  188.25
07/12/2019  208.5833333333333
08/12/2019  184.125
09/12/2019  210.16666666666663
10/12/2019  315.4166666666667

我想移动文件末尾的前两行。我怎么能用 pandas 做到这一点?该文件是一个示例,实际上可能还有更多行。

col_names=['day','val']
df_moved = pd.read_csv(o,sep='\t',header=None,names=col_names,skiprows=[1]) #for skipping the first two rows

使用 concat 按位置选择行:

df1 = pd.concat([df.iloc[2:], df.iloc[:2]])

DataFrame.reindex 附加索引值:

df1 = df.reindex(df.index[2:].append(df.index[:2]))

np.r_的解决方案:

df1 = df.iloc[np.r_[2:len(df), 0:2]]

print (df1)
          day         val
2  03/12/2019  213.291667
3  04/12/2019  187.916667
4  05/12/2019  191.875000
5  06/12/2019  188.250000
6  07/12/2019  208.583333
7  08/12/2019  184.125000
8  09/12/2019  210.166667
9  10/12/2019  315.416667
0  01/12/2019  234.750000
1  02/12/2019  303.666667

或使用ilocnp.arange:

>>> df.iloc[[*np.arange(2, len(df)), *np.arange(2)]]
   a   b
2  3   6
3  4   7
4  5   8
5  6   9
6  7  10
0  1   4
1  2   5
>>>