簡體   English   中英

使用pandas + python(有條件)在滾動窗口中計算不同的字符串

[英]Count distinct strings in rolling window using pandas + python (with a condition)

我想計算當前行和前5行(滑動窗口)之間存在的不同端口號的數量,並在出現相同地址時進行計算。 例如,

如果輸入是(csv文件):

ID      PORT     ADDRESS
1        21       ad3 
2        22       ad1  
3        23       ad2
4        25       ad2 
5        25       ad1
6        22       ad1 
7        22       ad1
8        21       ad4

輸出應為:

ID      PORT     ADDRESS      COUNT_DISC_PORT
1        21       ad3        -
2        22       ad1        -
3        23       ad2        - 
4        25       ad2        - 
5        25       ad1        - 
6        22       ad1        2 
7        23       ad1        3
8        21       ad4        1 

我已經閱讀了有關pandas中滾動功能的文檔,並且嘗試將group by和rolls組合在一起沒有成功。

我正在使用Python 3.7和pandas軟件包0.22。 對於任何反饋,我們都表示感謝。

for index, row in df.iterrows(): small_df = df[index - 5:index] df['uniques'][index] = len(small_df.unique())

這是我的簡要介紹。

好的,看來您的數據輸入與您向我們展示的df不匹配

df.groupby('ADDRESS').PORT.apply(lambda x : pd.Series(x).rolling(5,min_periods=1).apply(lambda y: len(set(y))))
Out[844]: 
0    1.0
1    1.0
2    1.0
3    2.0
4    2.0
5    2.0
Name: PORT, dtype: float64

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM