简体   繁体   English

在保持索引的同时对数据框中的元素进行排名

[英]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.

相关问题 pandas 数据帧,最大列数同时保持索引 - pandas data frame, max of columns while keeping index 重塑数据框架,同时保留分类变量 - Reshaping Data Frame while keeping categorical variables 排序多索引数据框保持索引排序 - Sorting multi index data frame keeping index sorted 无论窗口大小如何,如何在保持整个框架着色的同时保持框架中的元素向右对齐? - How do I keep elements in a frame justified to the right while keeping the entire frame coloured, regardless of the size of the window? 在索引为日期的情况下遍历数据框 - Iterating over a data frame while Index is a date 更改数据框索引值,同时保持其他列数据相同 - Change dataframe index values while keeping other column data same 如何按时间索引将两个pandas data.frame 合并为一个,同时保留两个pandas 的所有值 - How to merge two pandas data.frame into one, by time index, keeping all values from both of them 比较两个列表以返回一个列表,其中所有元素都为0,除了那些在保持索引时匹配的列表? - Compare two lists to return a list with all elements as 0 except the ones which matched while keeping index? 过滤常见值和排名的数据框 - filter data frame for common vales and rank 有没有办法获取索引元素与列表元素匹配的数据框元素 - Is there a way to get elements of a data frame where the index elements match the elements of a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM