簡體   English   中英

如何計算python中一定范圍內不為零的行數?

[英]How can I count the number of rows that are not zero in a certain range in python?

我有一個由0或1組成的熊貓系列。

2016-01-01    0
2016-01-02    1
2016-01-03    1
2016-01-04    0
2016-01-05    1
2016-01-06    1
2016-01-08    1
...

我想使用該系列制作一個數據框,添加另一個系列,該系列提供有關在一定時間內存在1的信息。

例如,如果期間為5天,則數據框看起來像

              Value   1s_for_the_last_5days
2016-01-01    0
2016-01-02    1
2016-01-03    1
2016-01-04    0
2016-01-05    1       3
2016-01-06    1       4
2016-01-08    1       4
...

另外,我想知道在以下情況下,是否可以計算一定范圍內不為零的行數。

              Value   Not_0_rows_for_the_last_5days
2016-01-01    0
2016-01-02    1.1
2016-01-03    0.4
2016-01-04    0
2016-01-05    0.6       3
2016-01-06    0.2       4
2016-01-08    10        4

謝謝您閱讀此篇。 如果您能給我任何解決方案或提示的問題,我將不勝感激。

您可以為此使用rolling ,從而創建一個大小合適的窗口,並在應用諸如sum之類的聚合時迭代給定的列。

首先創建一些虛擬數據:

import pandas as pd
import numpy as np

ser = pd.Series(np.random.randint(0, 2, size=10), 
                index=pd.date_range("2016-01-01", periods=10),
                name="Value")
print(ser)

2016-01-01    1
2016-01-02    0
2016-01-03    0
2016-01-04    0
2016-01-05    0
2016-01-06    0
2016-01-07    0
2016-01-08    0
2016-01-09    1
2016-01-10    0
Freq: D, Name: Value, dtype: int64

現在,使用滾動:

summed = ser.rolling(5).sum()
print(summed)

2016-01-01    NaN
2016-01-02    NaN
2016-01-03    NaN
2016-01-04    NaN
2016-01-05    1.0
2016-01-06    0.0
2016-01-07    0.0
2016-01-08    0.0
2016-01-09    1.0
2016-01-10    1.0
Freq: D, Name: Value, dtype: float64

最后,創建結果數據框:

df = pd.DataFrame({"Value": ser, "Summed": summed})
print(df)

            Summed  Value
2016-01-01     NaN      1
2016-01-02     NaN      0
2016-01-03     NaN      0
2016-01-04     NaN      0
2016-01-05     1.0      0
2016-01-06     0.0      0
2016-01-07     0.0      0
2016-01-08     0.0      0
2016-01-09     1.0      1
2016-01-10     1.0      0

為了計算任意值,請結合以下滾動窗口中的apply定義自己的聚合函數:

# dummy function to count zeros
count_func = lambda x: (x==0).sum()

summed = ser.rolling(5).apply(count_func)
print(summed)

您可以將0替換為原始系列的任何值或值的組合。

你想滾動

s.rolling('5D').sum()

df = pd.DataFrame({'Value': s, '1s_for_the_last_5days': s.rolling('5D').sum()})

pd.Series.rolling是一種有用的方法,但是您可以使用pd.Series.rolling的方法來做到這一點:

def rolling_count(l,rolling_num=5,include_same_day=True):
    output_list = []
    for index,_ in enumerate(l):
        start = index - rolling_num - int(include_same_day)
        end = index + int(include_same_day)
        if start < 0:
            start = 0
        output_list.append(sum(l[start:end]))
    return output_list

data = {'Value': [0, 1, 1, 0, 1, 1, 1],
        'date': ['2016-01-01','2016-01-02','2016-01-03','2016-01-04','2016-01-05','2016-01-06','2016-01-08']}

df = pd.DataFrame(data).set_index('date')

l = df['Value'].tolist()

df['1s_for_the_last_5days'] = rolling_count(df['Value'],rolling_num=5)

print(df)

輸出:

            Value  1s_for_the_last_5days
date                                    
2016-01-01      0                      0
2016-01-02      1                      1
2016-01-03      1                      2
2016-01-04      0                      2
2016-01-05      1                      3
2016-01-06      1                      4
2016-01-08      1                      5

暫無
暫無

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

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