Python 如何使用pandas对HTTP请求日志进行分组
我有一个HTTP请求日志。包括的功能有:捕获时间、ip、方法、url、内容、用户代理 所有这些信息都在csv文件中 我想将来自同一IP的所有请求分组,间隔10分钟 我怎样才能用熊猫做到这一点 示例数据集:Python 如何使用pandas对HTTP请求日志进行分组,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个HTTP请求日志。包括的功能有:捕获时间、ip、方法、url、内容、用户代理 所有这些信息都在csv文件中 我想将来自同一IP的所有请求分组,间隔10分钟 我怎样才能用熊猫做到这一点 示例数据集: date ip method url content agent 2019-04-2423:16:48.742466 187.20.211.99 职位 /交货/检查地点 贝罗=维拉&西达德=利马 Mozilla/5.0 (iPhone;CPU iPhone OS 12_2,如Mac OS
date ip method url content agent
- 2019-04-2423:16:48.742466
- 187.20.211.99
- 职位
- /交货/检查地点
- 贝罗=维拉&西达德=利马
- Mozilla/5.0 (iPhone;CPU iPhone OS 12_2,如Mac OS X)AppleWebKit/605.1.15 (KHTML-like壁虎)移动式/15E148
unique()
创建的列表
##https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe/55839330#55839330
def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')
在此之后,您可以连接您计划的任何内容
编辑:
# Set index to the date column
df.set_index('date', inplace = True)
# 10 minutes in nanoseconds
ns10min=10*60*1000000000
#Calculate the new 10 min.
df.index = pd.to_datetime(((df.index.astype(np.int64) // ns10min) * ns10min))
#Groupby both index and ip, then look at the first.
df.groupby([df.index, df['ip']]).first()
我使用Ben Pap的方法根据日期对IP进行分组。 之后,我得到了一个包含IP和时间间隔的数据帧。 要连接其他列并添加到此数据帧,我执行了以下操作:
content= []
row_iterator = test.iterrows()
for index, row in row_iterator:
texto = ""
resul = df2.loc[(df2[df2.columns[1]] == row[2]) & ((row[0] < df2.index) & (df2.index < row[0] + pd.Timedelta(minutes=10) ) )]
for i, (_, current_row) in enumerate(resul.iterrows()):
texto += " " + current_row.values[2] + " " + current_row.values[3] + " " + current_row.values[4]
content.append(texto)
content=[]
行迭代器=test.iterrows()
对于索引,行迭代器中的行:
texto=“”
结果=df2.loc[(df2[df2.columns[1]]==第[2]行]&((第[0]行
所以你只关心时间和ip,其他信息不重要?你需要在同一时间跨度内对该IP进行计数吗?我想根据IP和每个请求之间的时间间隔对它们进行分组。(10分钟)。我想在同一行上显示的方法、url和内容。例如:POST url内容获取url2 conten2…同一IP是否在同一时间跨度内具有不同的方法url和内容?是的。每个请求的方法和内容可能不同。因此,如果是这样的话,您仍然只需要该IP的1行?似乎很有效。我只是不知道如何连接其他字段,因为它会用ip和时间间隔创建一个新的数据帧。有什么想法吗?很高兴看到你使用了最不常用的:-)@WeNYoBen-yup!我非常透彻地阅读了这篇文章,以了解不同方法的所有优缺点,而您的方法非常方便:D@LuccaZenobio所以这就是为什么我之前问你们问题的原因,如果一个IP地址在10分钟内出现两次,并且有其他不同的列,你们不能把它合并,所以它仍然是一行。除非你希望你的DF是真正广泛的重复列?我想把所有其他列的内容加入一个。就像你的提示一样,但是还有一列所有值都连接在一起。如果我至少能得到索引,我就能做到
content= []
row_iterator = test.iterrows()
for index, row in row_iterator:
texto = ""
resul = df2.loc[(df2[df2.columns[1]] == row[2]) & ((row[0] < df2.index) & (df2.index < row[0] + pd.Timedelta(minutes=10) ) )]
for i, (_, current_row) in enumerate(resul.iterrows()):
texto += " " + current_row.values[2] + " " + current_row.values[3] + " " + current_row.values[4]
content.append(texto)