簡體   English   中英

使用 pandas 從數據幀中提取數據

[英]Extract the data from the data-frame using pandas

我有以下數據框。

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

所以,像這樣我有一個 dataframe 有更多這樣的數據。 現在,我正在嘗試的是我有這個我有Iddid column

現在還有一列Document_IDs ,它有id's ,所以,我想檢查一下這個Document ID's列中是否存在11文檔 ID,這也是一個數組。

所以,就像,

最后的 output 會像,

 did   avg  present    
   11   0.6    2
   13   0.9    1

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

我對此完全陌生。 所以任何小的幫助都會很棒。

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

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)

使用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

如果你想使用 pandas 原生解決方案,試試這個:

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

我沒有測試計算速度。

您還可以計算列表中某個項目的實例。

例如mylist.count(item)

因此,我將創建一個 function 將其應用於行:

def get_id(row):

    res = x['Document_IDs'].count(x['did'])

    return res

然后應用它,創建一個新的result列。

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

雖然我確信有人會提供更快的版本:)

給定以下輸入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM