Jojo
Jojo

Reputation: 1117

Reversing the order of values in a single column of a Dataframe

I was just wondering how to reverse the order of the values only in the Column Date in the dataframe df below, so that 2015-06-18 will be in the last row of Date. I've unfortunately only been able to find posts on how to change the order of all the columns in a dataframe.

       Date             YEAR  SHARE-VALUE  Cusip
0      2015-06-18         1    0.3293      APPL
1      2015-06-17         1    0.3528      GOOGL
2      2015-06-16         1    0.3507      LEN
3      2015-06-15         1    0.3581      TSD

Upvotes: 3

Views: 4314

Answers (1)

DSM
DSM

Reputation: 353549

One common approach to get pandas to ignore the index when doing assignment is to use the underlying .values:

In [142]: df["Date"] = df["Date"].values[::-1]

In [143]: df
Out[143]: 
         Date  YEAR  SHARE-VALUE  Cusip
0  2015-06-15     1       0.3293   APPL
1  2015-06-16     1       0.3528  GOOGL
2  2015-06-17     1       0.3507    LEN
3  2015-06-18     1       0.3581    TSD

This works because .values gives an unindexed numpy array (the dtype may vary):

In [146]: df["Date"].values
Out[146]: array(['2015-06-18', '2015-06-17', '2015-06-16', '2015-06-15'], dtype=object)

Similarly df["Date"] = df["Date"].tolist()[::-1] and so on will work as well, although probably more slowly.

Upvotes: 8

Related Questions