【问题标题】:How to efficiently count the number of smaller elements for every element in another column?如何有效地计算另一列中每个元素的较小元素的数量?
【发布时间】:2021-06-12 13:01:48
【问题描述】:

我有以下df

    name        created_utc
0   t1_cqug90j  1430438400
1   t1_cqug90k  1430438400
2   t1_cqug90z  1430438400
3   t1_cqug91c  1430438401
4   t1_cqug91e  1430438401
... ...         ...

name 的哪一列仅包含唯一值。我想创建一个字典,其键与name 列中的元素相同。每个这样的键的值是列中元素的数量created_utc严格小于比键的。我的预期结果类似于

{'t1_cqug90j': 6, 't1_cqug90k': 0, 't1_cqug90z': 3, ...} 

在这种情况下,created_utc 列中有 6 个元素严格小于小于 1430438400,即 t1_cqug90j 的对应值。我可以循环生成这样的字典。但是,在我的情况下,循环效率不高,行数超过 300 万。

能否请您详细说明一种更有效的方法?

import pandas as pd
import numpy as np
df = pd.read_csv('https://raw.githubusercontent.com/leanhdung1994/WebMining/main/df1.csv', header = 0)[['name', 'created_utc']]
df

更新:我发布了问题How to efficiently count the number of larger elements for every elements in another column? 并在那里收到了很好的答案。但是,我无法将代码修改为这种情况。如果有一个高效的代码可以适应这两种情况,那就太好了,即“严格更大”和“严格更小”。

【问题讨论】:

    标签: python python-3.x pandas group-by count


    【解决方案1】:

    我认为您需要sort_indexyour previous answer 进行降序排序:

    count_utc = df.groupby('created_utc').size().sort_index(ascending=False)
    print (count_utc)
    created_utc
    1430438401    2
    1430438400    3
    dtype: int64
    
    cumulative_counts = count_utc.shift(fill_value=0).cumsum()
    
    output = dict(zip(df['name'], df['created_utc'].map(cumulative_counts)) )
    
    print (output)
    {'t1_cqug90j': 2, 't1_cqug90k': 2, 't1_cqug90z': 2, 't1_cqug91c': 0, 't1_cqug91e': 0}
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2021-06-12
      • 2011-08-28
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多