【问题标题】:Extract the data from the data-frame using pandas使用 pandas 从数据框中提取数据
【发布时间】:2019-09-21 06:35:40
【问题描述】:

我有以下数据框。

PredictedFeature    Document_IDs                                   did  avg
   2000.0          [160, 384, 3, 217, 324, 11, 232, 41, 377, 48]    11  0.6
 2664.0        [160, 384, 3, 217, 324, 294,13,11]                     13  0.9

所以,像这样,我有一个数据框,其中包含更多这样的数据。现在,我正在尝试的是我有这个did column,其中我有Id

现在还有一列 Document_IDs,其中有 id's ,所以,我想检查 11 文档 ID 是否存在于这个 Document ID's 列中,这是一个类似 wise 的数组。

所以,就像,

最终的输出是这样的,

 did   avg  present    
   11   0.6    2
   13   0.9    1

2 是文档 ID 11 出现在此 Document Id's column 中的 2 倍。

我对此完全陌生。所以任何小的帮助都会很棒。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用Countermap 的解决方案

    import collections
    c = collections.Counter(df.Document_IDs.sum())    
    df['Present'] = df.did.map(c)
    
    df[['did', 'avg', 'Present']]
    
    Out[584]:
       did  avg  Present
    0  11   0.6  2
    1  13   0.9  1
    

    【讨论】:

    • @jezrael:感谢您指出先前解决方案中的错误。我切换到Counter :)
    • 是的,它更好,只是为了性能sum 是扁平化列表的更差解决方案(但看起来最好;))
    • @jezrael:呵呵……我同意。我喜欢它的简单:)。 itertools.chain 是扁平化列表的最佳选择,所以我已经对你的列表投了赞成票 :)
    【解决方案2】:

    您可以使用DataFrame.pop 提取列Document_IDs,然后通过chain.from_iterable 展平值,因此sum 可能在生成器中与apply 匹配值:

    import ast
    from  itertools import chain
    
    df['Document_IDs'] = df['Document_IDs'].fillna('[]').apply(ast.literal_eval)
    
    s = list(chain.from_iterable(df.pop('Document_IDs')))
    
    df['pres'] = df['did'].map(lambda x: sum(y == x for y in s))
    print (df)
       PredictedFeature  did  avg  pres
    0            2000.0   11  0.6     2
    1            2664.0   13  0.9     1
    

    或者:

    import ast
    from itertools import chain
    from collections import Counter
    
    df['Document_IDs'] = df['Document_IDs'].fillna('[]').apply(ast.literal_eval)
    
    df['pres'] = df['did'].map(Counter(chain.from_iterable(df.pop('Document_IDs'))))
    print (df)
       PredictedFeature  did  avg  pres
    0            2000.0   11  0.6     2
    1            2664.0   13  0.9     1
    

    编辑:

    from ast import literal_eval
    
    def literal_eval_cust(x):
        try:
            return literal_eval(x)
        except Exception:
            return []
    
    
    df['Document_IDs'] = df['Document_IDs'].apply(literal_eval_cust)
    

    【讨论】:

    • Document_ID 的数据类型是对象。扁平化它给了我一个错误。 'float' 对象不可迭代
    • @ganeshkaspate - print (type(df.loc[1, 'Document_IDs'])) 是什么?
    • 这就是我得到的
    • @ganeshkaspate - 所以在我的解决方案之前使用df['Document_IDs'] = df['Document_IDs'].apply(ast.literal_eval)
    • 错误的节点或字符串:nan
    【解决方案3】:

    如果你想使用 pandas 原生解决方案,试试这个:

    df['pres'] = df.apply(lambda x: list(x['Document_IDs']).count(x['did']), axis=1)
    

    我没有测试计算速度。

    【讨论】:

    • 嘿,我收到此错误“'float' object is not iterable”,'发生在索引 56')
    【解决方案4】:

    您还可以计算列表中某个项目的实例。

    例如mylist.count(item)

    所以我会创建一个函数来将其应用于行:

    def get_id(row):
    
        res = x['Document_IDs'].count(x['did'])
    
        return res
    

    然后应用它,创建一个新的result 列。

    df['result'] = df.apply(get_id,axis=1)
    

    虽然我确信有人会提供更快的版本:)

    【讨论】:

      【解决方案5】:

      给定以下输入:

      df = pd.DataFrame([[[3,4,5,6,3,3,5,4], 3], [[1,4,7,8,4,5,1], 4]], columns=['Document_IDs','did'])
      

      一行:

      df['Present'] = df.apply(lambda row: row.Document_IDs.count(row.did), axis=1)
      

      如果您想打印您感兴趣的结果:

      print(df[['did', 'avg', 'Present']])
      
         did  avg  Present
      0    3  0.6        3
      1    4  0.8        2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 2021-04-01
        • 2016-06-07
        • 1970-01-01
        • 1970-01-01
        • 2017-10-01
        相关资源
        最近更新 更多