鍍金池/ 問(wèn)答/Python  網(wǎng)絡(luò)安全/ 將某一文件按附圖所示方法輸出,該如何做?

將某一文件按附圖所示方法輸出,該如何做?

圖片描述

圖片描述

列為match的值區(qū)間,行 為QName的值
意思為求每個(gè)QName下的match值在各個(gè)區(qū)間出現(xiàn)的次數(shù)

回答
編輯回答
枕頭人

透視表方式

import pandas as pd
from random import randint

data = [[randint(0, 99), randint(0, 10)] for _ in range(10)]

df = pd.DataFrame(data, columns=['match', 'Qname'])
df['interval'] = df['match'].apply(lambda x: '{0}-{1}'.format(x//10 * 10 + 1 if x//10 >0 else 0, (x//10 + 1) * 10))

print pd.pivot_table(df, index='Qname', columns='interval', aggfunc=len, fill_value=0)
2017年3月17日 03:29
編輯回答
柚稚
import pandas as pd
df = pd.DataFrame([[100, 0],
    [92, 1],
    [100, 1],
    [40, 1],
    [98, 1],
    [98, 1],
    [98, 1],
    [98, 1],
    [98, 1],
    [98, 1],
    [100, 2],
    [100, 3],
    [100, 4],
    [78, 4],
    [100, 5],
    [68, 5],
    [47, 5]], columns=['match', 'Qname'])

def f(df):
    r = [len(df[(df['match'] > (i * 10 if i != 0 else -1)) & (df['match'] <= (i + 1) * 10)]) for i in range(10)]
    return pd.DataFrame([r], columns=['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '81-90', '91-100'])

df.groupby('Qname').apply(f)

一行模式

df.groupby('Qname').apply(lambda df:pd.DataFrame([[len(df[(df['match'] > (i * 10 if i != 0 else -1)) & (df['match'] <= (i + 1) * 10)]) for i in range(10)]], columns=['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '81-90', '91-100']))

2018年3月11日 13:58