【问题标题】:How can I do multiple pandas dataframes samples iterating over a dictionary?如何在字典上迭代多个 pandas 数据帧样本?
【发布时间】:2021-07-28 01:19:16
【问题描述】:

我有一本这样的字典:

 dic= {'AGS': array([1, 1, 1, 2, 2, 2, 3, 3, 3], dtype=int64),
'CM': array([1, 1, 2, 2], dtype=int64),
'COA': array([1, 1, 1, 2, 2, 3, 3], dtype=int64),
'COL': array([1, 2], dtype=int64)}

还有这样的数据框:

c = pd.DataFrame(data={'CTY':['AGS', 'AGS', 'AGS', 'AGS', 'AGS', 'AGS', 
                          'AGS', 'AGS', 'AGS', 'CM',  'CM',   'CM', 
                          'CM',  'COA', 'COA', 'COA', 'COA', 'COA', 
                          'COA', 'COA', 'COL', 'COL'],
                   'DIST':[1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2, 1, 
                         1, 1, 2, 2, 3, 3, 1, 2],
                   'FA':[350, 320, 350, 360, 380, 380, 480,480,488,
                         780, 320, 310, 250, 141, 564, 564, 437, 438,
                         287, 287, 560, 560],
                   'ID':[1, 1, 2, 2, 3, 1, 2, 3, 1, 1, 1, 2, 2, 2, 
                         3, 3, 1, 2, 3, 3, 1, 2],
                   'LTT':['A', 'A', 'B', 'B', 'B', 'C',
                          'C', 'C', 'B', 'C', 'A', 'E',
                          'S', 'B', 'B', 'C', 'C', 'A',
                          'C', 'A', 'E', 'S']
                   })

我想到的可能是使用字典以某种方式迭代数据帧,然后生成我真正需要的样本,该样本依赖于过滤后的 CTYDIST 列,如下所示,那么我是否将这些结果连接起来:

    df1=c[(df['CTY'] == 'AGS') & 
   (df['DIST'] == 1)].sample(n=2)
    df2=c[(df['CTY'] == 'AGS') & 
   (df['DIST'] == 2)].sample(n=2)
    df3=c[(df['CTY'] == 'AGS') & 
   (df['DIST'] == 3)].sample(n=2)
    df4=c[(df['CTY'] == 'CM') & 
   (df['DIST'] == 1)].sample(n=2)
    df5=c[(df['CTY'] == 'CM') & 
   (df['DIST'] == 2)].sample(n=2)
               .
               .
               .
    dfn=c[(df['CTY'] == 'COL') & 
   (df['DIST'] == 2)].sample(n=2)  

    pd.concat([df1,df2,df3, df4, df5, dfn])      

你有什么想法?我想获得尽可能快的输出,我将不胜感激。也许有一个列表理解

【问题讨论】:

    标签: python pandas dictionary list-comprehension


    【解决方案1】:

    IIUC,你可能需要字典理解:

    d = {key: c[c['CTY'].eq(key) & c['DIST'].isin(set(val))].sample(n=2) 
         for key,val in dic.items()}
    

    发布后您可以访问每个键来访问数据框:

    例子:

    print(d['AGS'])
    
       CTY  DIST   FA  ID LTT
    3  AGS     2  360   2   B
    1  AGS     1  320   1   A
    

    用于连接:

    pd.concat(d) #this will keep the identifier
    

    pd.concat((c[c['CTY'].eq(key) & c['DIST'].isin(set(val))].sample(n=2) 
               for key,val in dic.items()))
    

    【讨论】:

    • 可能是这样,但我想要的是为 dict 中与其键相关的每个唯一数字获取 2 个样本
    • @Richard21 这就是它的作用,尝试定义 d 的代码然后尝试 pd.concat(d) ,这是您的虚拟代码的复制
    • @Richard21 或者如果您不想要密钥,请尝试最后一段代码
    • 是的,我已经尝试过了,但我仍然希望输出为 DIST 的每个唯一值采样 n=2。我的意思是,对于 DIST 列中的值 1 和 2,预期的输出将是 4 行 @anky
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2016-07-12
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    相关资源
    最近更新 更多