Skip to main content
 首页 » 编程设计

python之+= 更新 pandas datadame 中的行

2024年12月31日10zhengyun_ustc

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

    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,因为它只出现在文件 1 中。第一列是系统调用 (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 更新频率(应该是 +=)。我正在 pandas 中寻找它的等价物。

编辑-我试过了

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

但我得到了 KeyError: 'clock_gettime'

请您参考如下方法:

由于您使用的是 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