+ = обновление строк в dandadame - PullRequest
0 голосов
/ 25 мая 2018

У меня есть куча файлов в папке, откуда я читаю каждый файл (где первый столбец - слова, а второй - цифры). Они выглядят примерно так -

    file1  file2
    a  2    a 3
    b  3    b 1 
    c  1     

    so the output would be -
       freq    file_freq
    a   5          2
    b   4          2
    c   1          1

Чтобы объяснить второй столбецвыходных данных a равно 2, потому что это происходит в обоих файлах, тогда как c равно 1, поскольку оно появляется только в файле file1.First столбец - это общее количество случаев, когда системные вызовы (a, b, c) появлялись в файлах.

часть кода-

 while line:
            words=line.split(" ")
            if words[0] in df.index:
                df.(words[0],'frequency')=int(words[1])+df.(words[0],'frequency')
                df.(words[0],'file_frequency')=df.(words[0],'file_frequency')+1

            else:
                df.loc[-1] = [words[0],words[1],1] 

Поэтому я ищу, если системный вызов, найденный в кадре данных, обновит частоту (которая должна быть + =).Я ищу его эквивалент в пандах.

edit- я попробовал

df[words[0]]['frequency'] += words[1]
df[words[0]]['file_frequency'] += 1 

, но получил KeyError: 'clock_gettime'

Ответы [ 2 ]

0 голосов
/ 25 мая 2018

Поскольку вы используете pandas, вы можете выполнить эту задачу в 2 этапа:

  1. Используйте pd.concat для объединения данных из ваших входных файлов в один кадр данных.
  2. Выполните одну groupby операцию с 2 вычислениями, как требуется.

Вот демонстрационная версия.

# read dataframes; in your code, you can use pd.read_csv
df1 = pd.DataFrame([['a', 2], ['b', 3], ['c', 1]])
df2 = pd.DataFrame([['a', 3], ['b', 1]])

# concatenate dataframes
df = pd.concat([df1, df2], ignore_index=True)

# perform groupby with 2 calculations
res = df.groupby(0)[1].agg({'freq': 'sum', 'file_freq': len})

print(res)

   freq  file_freq
0                 
a     5          2
b     4          2
c     1          1
0 голосов
/ 25 мая 2018

Вы можете использовать:

from collections import Counter
import glob

#add /*.* for read all files
currentdir = 'path/*.*'

#create 2 counters
c1 = Counter()
c2 = Counter()

#loop by files
for file in glob.glob(currentdir):
    print (file)

    with open(file) as f:
        for line in f:
           #split by rsplit - right split by first whitespace
           k, v = line.rsplit(' ', 1)
           #remove traling whitesapces
           k, v = k.strip(), v.strip()
           #get counts
           c1[k] += 1
           #get sums
           c2[k] += int(v)

#create final DataFrame only once by counters
df = (pd.DataFrame({'frequency':c2, 'file_frequency':c1})
       .rename_axis('system_call')
       .reset_index())
print (df)
  system_call  frequency  file_frequency
0           a          5               2
1           b          4               2
2           c          1               1

Другое более медленное решение:

import glob

#add /*.* for read all files
currentdir = 'path/*.*'

n = ['system_call','val']
#create list of all DataFrames from csv
df = pd.concat([pd.read_csv(f, sep='\s+',header=None,names=n) for f in glob.glob(currentdir)])
print (df)
  system_call  val
0           a    2
1           b    3
2           c    1
0           a    3
1           b    1

#aggregate sum and count
df = (df.groupby('system_call')['val']
        .agg([('freq', 'sum'), ('file_freq', 'size')])
        .reset_index())
print (df)
  system_call  freq  file_freq
0           a     5          2
1           b     4          2
2           c     1          1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...