简体   繁体   English

Python 3:按最后一行的列值对 DF 的字典进行排序

[英]Python 3: Sort Dict of DF's by Column Value from Last Row

Dict of df's: df 的字典:

years = [2017, 2018, 2019]
dfcols = ['Count', 'Amount']
dataframedict = {'CatA': pd.DataFrame(data=[[1, 5], [2, 6], [3, 7]], columns=dfcols, index=years), 
                'CatB': pd.DataFrame(data=[[4, 8], [5, 9], [6, 19]], columns=dfcols, index=years), 
                'CatC': pd.DataFrame(data=[[7,11], [8,12], [9,13]], columns=dfcols, index=years)}

Need a list of dict keys sorted descending by 'Amount' in 2019, so ['CatB', 'CatC', 'CatA']需要在 2019 年按 'Amount' 降序排序的 dict 键列表,因此 ['CatB', 'CatC', 'CatA']

Tried, following this variations of:试过了,下面的这个变化:

for k in sorted(dataframedict, key=lambda df: df.Amount[-1], reverse=True):
    print(k)

Getting error: AttributeError: 'str' object has no attribute 'Amount'获取错误: AttributeError: 'str' object has no attribute 'Amount'

Thanks谢谢

If you just want a list, you can use a list comprehension and the .items method of the dictionary to retrieve the key and dataframe如果你只想要一个列表,你可以使用列表理解和字典的.items方法来检索键和数据.items

[
    k for k, df 
    in sorted(dataframedict.items(), key=lambda x: x[1].Amount.iloc[-1], reverse=True)
]
# returns:
['CatB', 'CatC', 'CatA']

You can convert your dict to a sort list of tuples:您可以将 dict 转换为元组排序列表:

for k, v in sorted(dataframedict.items(), key=lambda x: x[1].Amount.iloc[-1], reverse=True):
    print(k)

Output:输出:

CatB
CatC
CatA

Note that I am passing .items() to the sorted .请注意,我将.items()传递给sorted Each one is a tuple of length 2 ( x[0] is the key and x[1] is the value/df).每个都是长度为 2 的元组( x[0]是键, x[1]是值/df)。

Now, regarding your error: When you pass a dict in sorted, the keys of the dict are considered:现在,关于您的错误:当您在 sorted 中传递 dict 时,会考虑 dict 的键:

>>> a = {1: "ad", 0: "ads"}
>>> sorted(a, key=lambda x: x)
[0, 1]

Thus you are passing strings in the lambda因此,您在lambda中传递字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM