[英]Count occurences of integers starting with 4 in dataframe
我有一個 dataframe 形式如下:
index client_ip http_response_code
2022-07-23 05:10:10+00:00 172.19.0.1 300
2022-07-23 06:13:26+00:00 192.168.0.1 400
... ... ...
我需要按clientip
並計算列response
中數字 4xx 的出現次數,即整數出現的次數以 4 開頭。
我嘗試過的是以下內容:
df.groupby('client_ip')['http_response_code'].apply(lambda x: (str(x).startswith(str(4))).sum())
但我收到以下錯誤:
AttributeError: 'bool' object has no attribute 'sum'
但是,如果假設我需要找到 400 的出現次數,那么以下不會給出任何錯誤,盡管仍然是 boolean:
df.groupby('client_ip')['http_response_code'].apply(lambda x: (x==400).sum())
知道這里有什么問題嗎?
知道這里有什么問題嗎?
您的 function 將 Series 作為輸入,將其與值進行比較給出 boolean 值的 Series,可以將其相加,使用str
函數給出 str,它沒有.sum
。 使用.astype(str)
將每個值轉換為 str 而不是整個系列,例如
import pandas as pd
df = pd.DataFrame({"User":["A","A","B"],"Status":[400,301,302]})
grouped = df.groupby("User")["Status"].apply(lambda x:x.astype(str).str.startswith("4").sum())
print(grouped)
output
User
A 1
B 0
Name: Status, dtype: int64
IIUC,這應該適合你:
import pandas as pd
import numpy as np
np.random.seed(123)
df = pd.DataFrame({'client_id': np.random.choice([1, 2, 3], size=10, replace=True, p=None), 'http_response_code': np.random.choice([300, 400], size=10, replace=True, p=None)})
print(df[df.http_response_code.apply(lambda x: (str(x).startswith(str(4))))].groupby('client_id').count())
Dataframe:
client_id http_response_code
0 3 300
1 2 400
2 3 300
3 3 400
4 1 300
5 3 400
6 3 400
7 2 300
8 3 300
9 2 300
結果:
http_response_code
client_id
2 1
3 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.