首页 > 解决方案 > += 更新 pandas datadame 中的行

问题描述

我在读取每个文件的文件夹中有一堆文件(第一列是单词,第二列是数字)。它们看起来像这样 -

    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 中。第一列是系统调用(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] 

因此,我正在寻找在数据帧中找到的 if system_call 更新频率(应该是 +=)。我正在寻找它在熊猫中的等价物。

编辑-我试过了

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

但我得到了KeyError: 'clock_gettime'

标签: pythonpandasdataframe

解决方案


由于您使用的是pandas,因此您可以分两步执行此任务:

  1. 用于pd.concat将输入文件中的数据组合到单个数据框中。
  2. 根据需要执行具有 2 次计算的单个groupby操作。

这是一个演示。

# 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

推荐阅读