簡體   English   中英

識別非連續零的索引值

[英]Identify the index values of non-consecutive zeros

我有一個負數和零的熊貓數據框,帶有日期時間索引。

我希望能夠:(1)確定非連續非零值的開始和結束日期; (2) 這兩個日期之間的天數; (3) 這兩個日期之間的最小值

例如,如果我的數據框如下所示:

DATE        VAL  
2007-06-26  0.000000
2007-06-27  0.000000
2007-06-28  0.000000
2007-06-29 -0.006408
2007-07-02  0.000000
2007-07-03  0.000000
2007-07-04 -0.000003
2007-07-05  0.000000
2007-07-06  0.000000
2007-07-09  0.000000
2007-07-10 -0.018858
2007-07-11 -0.015624
2007-07-12  0.000000
2007-07-13  0.000000
2007-07-16 -0.008562
2007-07-17 -0.006587

我想要看起來像這樣的輸出:

START        END          DAYS  MIN
2007-06-29   2007-06-29   1     -0.006408
2007-07-04   2007-07-04   1     -0.000003
2007-07-10   2007-07-11   2     -0.018858
2007-07-16   2007-07-17   2     -0.008562

如果天數不包括周末(即 7/13 到 7/16 算作 1 天),那會更好,但我意識到這通常很復雜。

numpy.argmax/min方法似乎做了我想要的一個版本,但是根據文檔設置axis=1沒有返回我期望的索引值集合。

編輯:應該指定,尋找不需要循環的解決方案。

在 Pandas 0.25+ 中使用named-aggregation解決方案:

#convert DatetimeIndex to column
df = df.reset_index()
#filter values equal 0
m = df['VAL'].eq(0)
#create groups only for non 0 rows filtering with inverting mask by ~
g = m.ne(m.shift()).cumsum()[~m]
#aggregation by groups
df1 = df.groupby(g).agg(START=('DATE','first'),
                        END=('DATE','last'),
                        DAYS= ('DATE', 'size'),
                        MIN=('VAL','min')).reset_index(drop=True)
print (df1)
       START        END  DAYS       MIN
0 2007-06-29 2007-06-29     1 -0.006408
1 2007-07-04 2007-07-04     1 -0.000003
2 2007-07-10 2007-07-11     2 -0.018858
3 2007-07-16 2007-07-17     2 -0.008562

通過將字典傳遞給agg並最后設置新列名稱,可以解決熊貓 <0.25 的問題:

df = df.reset_index()
m = df['VAL'].eq(0)
g = m.ne(m.shift()).cumsum()[~m]

df1 = df.groupby(g).agg({'DATE':['first','last','size'], 'VAL':'min'}).reset_index(drop=True)
df1.columns = ['START','END','DAYS','MIN']
print (df1)
       START        END  DAYS       MIN
0 2007-06-29 2007-06-29     1 -0.006408
1 2007-07-04 2007-07-04     1 -0.000003
2 2007-07-10 2007-07-11     2 -0.018858
3 2007-07-16 2007-07-17     2 -0.008562

首先,您創建一個標志來查找非零記錄並將它們分配在相同的組中,然后分組並計算您想要的那些屬性。

(
    df.assign(Flag = np.where(df.VAL.ge(0), 1, np.nan))
    .assign(Flag = lambda x: x.Flag.fillna(x.Flag.cumsum().ffill()))
    .loc[lambda x: x.Flag.ne(1)]
    .groupby('Flag')
    .apply(lambda x: [x.DATE.iloc[0], x.DATE.iloc[-1], len(x), x.VAL.min()])
    .apply(pd.Series)
    .set_axis(['START','END','DAYS','MIN'], axis=1, inplace=False)
)


        START       END         DAYS    MIN
Flag                
3.0     2007-06-29  2007-06-29  1   -0.006408
5.0     2007-07-04  2007-07-04  1   -0.000003
8.0     2007-07-10  2007-07-11  2   -0.018858
10.0    2007-07-16  2007-07-17  2   -0.008562

這個與最初的解決方案(Allen)有一些相似的邏輯,但“適用”較少。 不確定性能比較。

# a new group begins when previous value is 0, but current is negative
df['NEW_GROUP'] = df['VAL'].shift(1) == 0
df['NEW_GROUP'] &= df['VAL'] < 0

# Group by the number of times a new group has showed up, which determines the group number.
# Directly return a Series from `apply` to obviate further transformations
print(df.loc[df['VAL'] < 0]
        .groupby(df['NEW_GROUP'].cumsum())
        .apply(lambda x: pd.Series([x.DATE.iloc[0], x.DATE.iloc[-1], x.VAL.min(), len(x)],
                        index=['START','END','MIN','DAYS'])))

輸出:

          START      END         MIN         DAYS
NEW_GROUP                                      
1         2007-06-29 2007-06-29 -0.006408     1
2         2007-07-04 2007-07-04 -0.000003     1
3         2007-07-10 2007-07-11 -0.018858     2
4         2007-07-16 2007-07-17 -0.008562     2

numpy解決方案, df是您的示例 DataFrame:

# get data to numpy
date = df.index.to_numpy(dtype='M8[D]')
val = df['VAL'].to_numpy()

# find switches between zero/nonzero
on,off = np.diff(val!=0.0,prepend=False,append=False).nonzero()[0].reshape(-1,2).T
# use switch points to calculate all desired quantities
out = pd.DataFrame({'START':date[on],'END':date[off-1],'DAYS':np.busday_count(date[on],date[off-1])+1,'MIN':np.minimum.reduceat(val,on)})
# admire
out
#        START        END  DAYS       MIN
# 0 2007-06-29 2007-06-29     1 -0.006408
# 1 2007-07-04 2007-07-04     1 -0.000003
# 2 2007-07-10 2007-07-11     2 -0.018858
# 3 2007-07-16 2007-07-17     2 -0.008562

你可以使用這個:首先從文件中讀取數據幀:

import pandas as pd
df=pd.read_csv("file.csv")

出去:

    DATE    VAL
0   2007-06-26  0.000000
1   2007-06-27  0.000000
2   2007-06-28  0.000000
3   2007-06-29  -0.006408
4   2007-07-02  0.000000
5   2007-07-03  0.000000
6   2007-07-04  -0.000003
7   2007-07-05  0.000000
8   2007-07-06  0.000000
9   2007-07-09  0.000000
10  2007-07-10  -0.018858
11  2007-07-11  -0.015624
12  2007-07-12  0.000000
13  2007-07-13  0.000000
14  2007-07-16  -0.008562
15  2007-07-17  -0.006587

和主要代碼:

from datetime import timedelta

last_date=0
min_val=0
mat=[]
st=0
for index, row in df.iterrows():
    if (row['VAL'])!=0:
        st=st+1
        datetime_object = datetime.strptime(row['DATE'], '%Y-%m-%d')
        if st==1:
            start=datetime_object
            last_date=start
            if row['VAL']<min_val:
                min_val=row['VAL']

        else:
            if last_date+timedelta(days=1)==datetime_object:
                last_date=datetime_object
                if row['VAL']<min_val:
                    min_val=row['VAL']


            else:
                arr=[]
                arr.append(str(start.date()))
                arr.append(str(last_date.date()))
                arr.append(((last_date-start).days)+1)
                arr.append(min_val)
                start=datetime_object
                last_date=datetime_object
                min_val=row['VAL']
                mat.append(arr)
arr=[]

arr.append(str(start.date()))
arr.append(str(last_date.date()))
arr.append(((last_date-start).days)+1)
arr.append(min_val)
mat.append(arr)
df = pd.DataFrame(mat, columns = ['start', 'end', 'days', 'min']) 
df

出去:

start   end days    min
0   2007-06-29  2007-06-29  1   -0.006408
1   2007-07-04  2007-07-04  1   -0.000003
2   2007-07-10  2007-07-11  2   -0.018858
3   2007-07-16  2007-07-17  2   -0.008562

暫無
暫無

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

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