How to add and reverse a new column according to an id column
<p>This is my first question at stackoverflow and I'm pretty new in the area of programming with python.</p>

<p><a href="http://i.stack.imgur.com/1bKY7.jpg" rel="nofollow">image of what I'm trying to do</a></p>

<p>As you can see in the picture column "id" and "period" are given. It's a csv dataset and I want to add a  new column named "newColumn", where the numbers from "period" are in a reversed order according to their "id values". I hope you understand my problem. </p>

<p>Thank you in advance.</p>

<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>:</p>

<pre><code>print (df)
   id  period
0   1       1
1   1       2
2   1       3
3   2       1
4   2       2
5   2       3
6   3       1
7   3       2
8   3       3

print (df.sort_values(by=['id','period'], ascending=[True, False]))
   id  period
2   1       3
1   1       2
0   1       1
5   2       3
4   2       2
3   2       1
8   3       3
7   3       2
6   3       1
</code></pre>

<p>Then if need create new column, convert sorted column to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> for not align by index:</p>

<pre><code>df['new'] = df.sort_values(by=['id','period'], ascending=[True, False])['period'].values
print (df)
   id  period  new
0   1       1    3
1   1       2    2
2   1       3    1
3   2       1    3
4   2       2    2
5   2       3    1
6   3       1    3
7   3       2    2
8   3       3    1
</code></pre>

python pandas numpy order reverse