2016-08-20 143 views
1

我追加3行與該代碼數據框:z = pandas.DataFrame.append(z, [{'Items': 'Foo'}, {'Items': 'Barr'}, {'Items': 'Options'}]),得到了如下的結果:重新排序行

Items   Last 12 Months 
0 Apple   48.674 
1 Dragon Fruit 8.786 
2 Milk   2.367 
3 Foo   3.336 
4 Barr   0.005 
5 Options  NaN 

是否可以移動最後3行「Foo, Barr, Options」成爲第一3行而不是?不改變索引..

回答

1

reindex怎麼樣?

In [4]: df 
Out[4]: 
      Items Last 12 Months 
0   Apple   48.674 
1 Dragon Fruit   8.786 
2   Milk   2.367 

In [5]: z = pd.DataFrame([{'Items': 'Foo', 'Last 12 Months': 3.336}, {'Items': 'Barr', 'Last12Months': 0.005}, {'Items': 'Options'}]) 

In [6]: z 
Out[6]: 
    Items Last 12 Months 
0  Foo   3.336 
1  Barr   0.005 
2 Options    NaN 

In [7]: df = df.append(z, ignore_index = True) 

In [8]: df 
Out[8]: 
      Items Last 12 Months 
0   Apple   48.674 
1 Dragon Fruit   8.786 
2   Milk   2.367 
3   Foo   3.336 
4   Barr   0.005 
5  Options    NaN 

In [9]: prev_len = len(df) - len(z) 

In [10]: df = df.reindex(range(prev_len, len(df)) + range(prev_len)) 

In [11]: df 
Out[11]: 
      Items Last 12 Months 
3   Foo   3.336 
4   Barr   0.005 
5  Options    NaN 
0   Apple   48.674 
1 Dragon Fruit   8.786 
2   Milk   2.367 
+0

嗯,但總共有670行..我剛剛給了整個人口的片段。 –