簡體   English   中英

熊貓 - 檢查列中的數字是否在行中

[英]Pandas - Check if Numbers in Column are in row

我有一個pandas數據幀如下:

user_id product_id order_number
1       1          1
1       1          2
1       1          3
1       2          1
1       2          5
2       1          1
2       1          3
2       1          4
2       1          5
3       1          1
3       1          2
3       1          6

我想查詢這個df的最長條紋(沒有跳過order_number)和最后一條條紋(自上一個order_number以來)。

理想的結果如下:

user_id product_id longest_streak last_streak
1       1          3              3
1       2          0              0
2       1          3              3
3       1          2              0

我很欣賞這方面的任何見解。

我仍然不太確定你如何定義last_streak ,但是,假設不重復用戶和產品的相同組合,下面計算最長的條紋:

import itertools

def extract_streaks(data):
   streaks = [len(list(rows)) for d,rows in itertools.groupby(data) if d==1.0]
   return max(streaks) + 1 if streaks else 0

df['diffs'] = df.order_number.diff()
df.groupby(['user_id', 'product_id'])['diffs'].apply(extract_streaks)
#user_id  product_id
#1        1             3
#         2             0
#2        1             3

你可以試試

s=df.assign(key=1).set_index(['user_id','product_id','order_number']).key.unstack()  s=s.notnull().astype(int).diff(axis=1).fillna(0).ne(0).cumsum(axis=1).mask(s.isnull())    
s=s.apply(pd.value_counts,1)
s=s.mask(s==1,0)    
pd.concat([s.max(1),s.ffill(axis=1).iloc[:,-1]],1)
Out[974]: 
                    0.0  2.0
user_id product_id          
1       1           3.0  3.0
        2           0.0  0.0
2       1           3.0  3.0

使用循環和defaultdict

a = defaultdict(lambda:None)
longest = defaultdict(int)
current = defaultdict(int)
for i, j, k in df.itertuples(index=False):
    if a[(i, j)] == k - 1:
        current[(i, j)] += 1 if current[(i, j)] else 2
        longest[(i, j)] = max(longest[(i, j)], current[(i, j)])
    else:
        current[(i, j)] = 0
        longest[(i, j)] |= 0
    a[(i, j)] = k

pd.concat(
    [pd.Series(d) for d in [longest, current]],
    axis=1, keys=['longest_streak', 'last_streak']
).rename_axis(['user_id', 'product_id']).reset_index()

   user_id  product_id  longest_streak  last_streak
0        1           1               3            3
1        1           2               0            0
2        2           1               3            3
3        3           1               2            0

暫無
暫無

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

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