使用熊猫从数据框中提取数据

时间:2019-09-20 09:12:11

标签: python pandas numpy

我有以下数据框。

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的{​​{1}}

现在还有一个列Id,其中有Document_IDs,因此,我想检查天气,id's列中的11文档ID是否为明智的数组。

所以,像

最终输出将是,

Document ID's

2是此 did avg present 11 0.6 2 13 0.9 1 中存在文档ID 11的2倍。

我对此完全陌生。因此,任何小的帮助都将是巨大的。

5 个答案:

答案 0 :(得分:1)

您可以使用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)

答案 1 :(得分: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

答案 2 :(得分:0)

如果您想使用熊猫本机解决方案,请尝试以下操作:

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

我尚未测试计算速度。

答案 3 :(得分:0)

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

例如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)

尽管我敢肯定有人会带来更快的版本:)

答案 4 :(得分:0)

提供以下输入:

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
相关问题