【问题标题】:Counting occurrences of IDs in pandas dataframe计算熊猫数据框中 ID 的出现次数
【发布时间】:2021-06-15 23:54:45
【问题描述】:

我有几个数据帧,每个几千行看起来与此类似:

heifers_df

       id   y     ins               
200316157 123 2004121 
200316157 456 2004121 
200316157 789 2004121 
200519776 456 2007234 
200519776 789 2007234 
200812334 123 2010333 
200812334 789 2010333 
200812334 345 2010333 
200812334 567 2010333 

我想使用 python (pandas 或 numphy?) 来计算每个 ID 的出现次数,总出现次数 (T)每次出现的次数 (No) :

heifers_df

       id    y      ins  T  No          
200316157  123  2004121  3   1
200316157  456  2004121  3   2
200316157  789  2004121  3   3
200519776  456  2007234  2   1
200519776  789  2007234  2   2
200812334  123  2010333  4   1
200812334  789  2010333  4   2
200812334  345  2010333  4   3
200812334  567  2010333  4   4

我在 Fortran Counting frequency of variables in text data in Fortran 中得到了解决这个问题的帮助 但现在我正试图在 python 中完成同样的工作。

基于 Fortran 代码和我对 python 和 pandas 的初学者知识,这是我尝试对第一个数据帧执行的操作:

i1 = 0
# set i0, i1
#  i0: line where specific user id starts
#  i1: line where specific user id ends
for i in range(len(heifers_df)) :
    i0 = i1 + 1
    same_id = True
    while same_id == True :
        heifers_df.loc[
            heifers_df["id"[i]] != heifers_df["id"[i0]],     #How do I reference each row within the column?
            same_id ] = False
    i1 = i
    heifers_df["T"] = i1-i0+1
    heifers_df["No"] = i-i0+1

但是当我运行它时,我得到一个错误:

....  heifers_df["id"[i]] != heifers_df["id"[i0]],
     KeyError: 'i'

我是不是走错了方向?

我尝试搜索类似的问题,并且看到了 group by 和 count 操作,但我还没有看到将结果与问题中的 ID 粘合并计算每个问题的操作。 任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    IIUC,如果所有唯一的 id 都可以排序成连续的块。

    df['T'] = df.groupby('id')['id'].transform('count')
    df['No'] = df.groupby('id')['id'].cumcount() + 1
    df
    

    输出:

              id    y      ins  T  No
    0  200316157  123  2004121  3   1
    1  200316157  456  2004121  3   2
    2  200316157  789  2004121  3   3
    3  200519776  456  2007234  2   1
    4  200519776  789  2007234  2   2
    5  200812334  123  2010333  4   1
    6  200812334  789  2010333  4   2
    7  200812334  345  2010333  4   3
    8  200812334  567  2010333  4   4
    

    【讨论】:

    • 这确实有效!谢谢你。我确实收到以下错误消息:试图在 DataFrame 的切片副本上设置值。尝试改用 .loc[row_indexer,col_indexer] = value 查看文档中的警告:pandas.pydata.org/pandas-docs/stable/user_guide/… df['No'] = df.groupby('id')['id'].cumcount() + 1跨度>
    • 创建 df.使用 .copy() 在自己的内存空间中创建一个全新的数据帧。
    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多