python - += 更新 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'
解决方案
由于您使用的是pandas
,因此您可以分两步执行此任务:
- 用于
pd.concat
将输入文件中的数据组合到单个数据框中。 - 根据需要执行具有 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
推荐阅读
- jquery - How to conditionally set column to editable in kendo grid?
- postgresql - Postgresql json_each equivalent in Presto
- bluetooth - Code not executing when command comes over bluetooth
- python - What benefits does the % formatter offer in comparison to f strings?
- github - I want to push git easily
- linechart - 悬停时的着色线对于带有点的线与仅在 vega-lite 中的线的工作方式不同
- node.js - How to pass variable into function [ different file] using node js express
- python - 为什么在 python 中执行 argparse 时出现错误
- python - 为什么通过 Matlab 在调用 Python websocket 函数时添加关键字参数会引发错误?
- javascript - How can I trigger a method when end date is changed