[英]Rank elements in a data frame while keeping index
I'm using the following formula to gather the top 20 elements for each row in a data frame. 我正在使用以下公式来收集数据框中每一行的前20个元素。 It works great but it is dropping the index column from the df_returns but I'd like to keep them.
它工作得很好,但是它从df_returns中删除了索引列,但我想保留它们。 I was using dates as the index in the df_returns data frame and I'd like to have the same dates corresponding to the new data in the df_rank data frame.
我将日期用作df_returns数据框中的索引,并且我希望具有与df_rank数据框中的新数据相对应的相同日期。
df_rank = pd.DataFrame({n: df_returns.T[col].nlargest(21).index.tolist() for n, col in enumerate(df_returns.T)}).T
For example, let's say I was wanting to get the top 3 from the following data frame: 例如,假设我想从以下数据框中获得前三名:
A B C D E
1/1/2014 5 4 6 8 1
2/1/2014 2 1 6 3 1
3/1/2014 8 2 3 5 1
The results I'm getting currently are: 我目前得到的结果是:
0 D C A
1 C D A
2 A D C
The results I'd like to get are: 我想要得到的结果是:
1/1/2014 D C A
2/1/2014 C D A
3/1/2014 A D C
您可以使用set_index
来设置原始数据帧的原始索引:
df_rank.set_index(df_returns.index)
If you want to apply a function to each row of a data frame, apply
is often your best bet (I've rewritten your function a bit too): 如果要将功能应用于数据框的每一行,那么
apply
通常是最好的选择(我也对函数进行了一些重写):
d.apply(lambda r: r.sort_values(ascending = False)[0:3].index.tolist(), axis=1)
Out[88]:
1/1/2014 [D, C, A]
2/1/2014 [C, D, A]
3/1/2014 [A, D, C]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.