【问题标题】:Access the first element of a sorted list访问排序列表的第一个元素
【发布时间】:2023-04-07 04:22:01
【问题描述】:

下面是原表:

identifier            comments_count
2353962646372849000        4153
2353962646372849028        6102
2342365172189273063        3936
2353962646372849567        5202
2342365172189273168        3076
df = pd.DataFrame({

    'identifier': [2353962646372849000, 2353962646372849028, 2342365172189273063, 2353962646372849567 , 2342365172189273168],

    'comments_count': [4153, 6102, 3936, 5202, 3076],
})

我想访问 dfsorted.identifier 的第一个元素,它是一个排序列表。

查询的输出应为'2353962646372849028'

dfsorted = df.sort_values('comments_count',ascending=False)

identifier            comments_count
2353962646372849028        6102
2353962646372849567        5202
2353962646372849000        4153
2342365172189273063        3936
2342365172189273168        3076

查询

dfsorted['identifier'][0] 

但是一直返回'2353962646372849000'(排序前标识符的第一个元素)。 如何解决这个问题?

【问题讨论】:

  • 使用dfsorted = df.sort_values('comments_count',ascending=False, ignore_index=True)

标签: python python-3.x pandas list dataframe


【解决方案1】:

你可以使用:

dfsorted.iloc[0,:]['identifier']

或更简单:

dfsorted.iloc[0,0]

结果:

2353962646372849028

【讨论】:

    【解决方案2】:
    dfs=df.groupby('comments_count', as_index=False).apply(lambda x: x.nlargest(1, columns=['identifier'])).reset_index(level=1, drop=1)
    

    重置索引会正常工作,结果如你所愿:

    2342365172189273168
    

    【讨论】:

      【解决方案3】:
      dfsorted = df.sort_values('comments_count', ascending=False).reset_index(drop=True)
      

      使用它来重置索引:D

      排序列表不会更新索引,如果您打印表格,您将看到索引没有更新。通过使用reset_index(drop=True),您可以创建新索引并删除旧索引。如果您忽略 drop=True,它会将旧索引保存在额外的列中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2021-09-06
        • 1970-01-01
        • 2021-11-12
        相关资源
        最近更新 更多