Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...