簡體   English   中英

python pandas字符串列時間滾動不重復計數

[英]python pandas string column time rolling distinct count

由於我想計算移動時間窗口(60秒)中列A的唯一數量:

fn = lambda x: len(np.unique(x)) 
df = pd.DataFrame({'A':['a', 'b', 'a', 'b', 'e'], 'B': [0, 1, 2, 3, 4]},
                index = [pd.Timestamp('20130101 09:01:00'),
                         pd.Timestamp('20130101 09:01:32'),
                         pd.Timestamp('20130101 09:02:03'),
                         pd.Timestamp('20130101 09:02:25'),
                         pd.Timestamp('20130101 09:03:06')])


df[['A']].rolling('60s').apply(fn)

我期望結果為

2013-01-01 09:01:00 1
2013-01-01 09:01:32 2
2013-01-01 09:02:03 2
2013-01-01 09:02:25 2
2013-01-01 09:03:06 2

但是,結果是:

2013-01-01 09:01:00 a
2013-01-01 09:01:32 b
2013-01-01 09:02:03 a
2013-01-01 09:02:25 b
2013-01-01 09:03:06 e

有什么問題?

您可以使用B列而不是A列:

a = df[['B']].rolling('60s').apply(fn)
print (a)
                       B
2013-01-01 09:01:00  1.0
2013-01-01 09:01:32  2.0
2013-01-01 09:02:03  2.0
2013-01-01 09:02:25  3.0
2013-01-01 09:03:06  2.0

如果需要轉換為int

a = df[['B']].rolling('60s').apply(fn).astype(int)
print (a)
                     B
2013-01-01 09:01:00  1
2013-01-01 09:01:32  2
2013-01-01 09:02:03  2
2013-01-01 09:02:25  3
2013-01-01 09:03:06  2

如果沒有列,則可以創建它:

a = df.assign(B=np.arange(len(df.index)))[['B']].rolling('60s').apply(fn).astype(int)
print (a)
                     B
2013-01-01 09:01:00  1
2013-01-01 09:01:32  2
2013-01-01 09:02:03  2
2013-01-01 09:02:25  3
2013-01-01 09:03:06  2

df['B'] = np.arange(len(df.index))
a = df[['B']].rolling('60s').apply(fn).astype(int)
print (a)
                     B
2013-01-01 09:01:00  1
2013-01-01 09:01:32  2
2013-01-01 09:02:03  2
2013-01-01 09:02:25  3
2013-01-01 09:03:06  2

EDIT1:

df['B'] = np.arange(len(df.index))
a = df.groupby('A')[['B']].rolling('60s').apply(fn).astype(int)
print (a)
                       B
A                       
a 2013-01-01 09:01:00  1
  2013-01-01 09:02:03  1
b 2013-01-01 09:01:32  1
  2013-01-01 09:02:25  2
e 2013-01-01 09:03:06  1

只需嘗試這種方式:

In [40]: import pandas as pd

In [41]: fn = lambda x: len(np.unique(x)) 
    ...: df = pd.DataFrame({'A':['a', 'b', 'c', 'd', 'e'], 'B': [0, 1, 2, 3, 4]},
    ...:                 index = [pd.Timestamp('20130101 09:01:00'),
    ...:                          pd.Timestamp('20130101 09:01:32'),
    ...:                          pd.Timestamp('20130101 09:02:03'),
    ...:                          pd.Timestamp('20130101 09:02:25'),
    ...:                          pd.Timestamp('20130101 09:03:06')])

In [42]: df[['B']] = df[['B']].rolling('60s').apply(fn).astype(int)

In [43]: df[['']] = df[['B']]

In [44]: df[['']]
Out[44]: 

2013-01-01 09:01:00  1
2013-01-01 09:01:32  2
2013-01-01 09:02:03  2
2013-01-01 09:02:25  3
2013-01-01 09:03:06  2

In [45]: 

暫無
暫無

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

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