簡體   English   中英

Pandas相當於整數索引的重采樣

[英]Pandas' equivalent of resample for integer index

我正在尋找一個pandas等效的resample方法,用於數據幀,它不是DatetimeIndex而是整數數組,甚至可能是浮點數。

我知道,對於某些情況(例如, 這個 ),重新采樣方法可以通過reindex和插值輕松替換,但在某些情況下(我認為)它不能。

例如,如果我有

df = pd.DataFrame(np.random.randn(10,2))
withdates = df.set_index(pd.date_range('2012-01-01', periods=10))
withdates.resample('5D', np.std)

這給了我

                   0         1
2012-01-01  1.184582  0.492113
2012-01-06  0.533134  0.982562

但我不能用df和resample產生相同的結果。 所以我正在尋找可以起作用的東西

 df.resample(5, np.std)

這會給我

          0         1
0  1.184582  0.492113
5  0.533134  0.982562

這種方法存在嗎? 我能夠創建此方法的唯一方法是手動將df分成較小的數據幀,應用np.std然后將所有內容連接起來,我覺得這很慢,而且根本不聰明。

干杯

建立

import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(20, 2), columns=['A', 'B'])

您需要創建標簽以自行分組。 我用的是:

(df.index.to_series() / 5).astype(int)

為了獲得一系列的值,如[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ...] groupby [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ...]然后在groupby使用它

您還需要為新數據幀指定索引。 我用的是:

df.index[4::5]

獲得當前指數從第5個位置開始(因此是4 )和之后的每個第5個位置。 它看起來像[4, 9, 14, 19] 我可以用df.index[::5]來完成這個以獲得起始位置,但我選擇了結束位置。

# assign as variable because I'm going to use it more than once.
s = (df.index.to_series() / 5).astype(int)

df.groupby(s).std().set_index(s.index[4::5])

好像:

           A         B
4   0.198019  0.320451
9   0.329750  0.408232
14  0.293297  0.223991
19  0.095633  0.376390

其他考慮

這相當於下采樣。 我們還沒有解決抽樣問題。

為了更頻繁地從我們生成的數據幀索引返回到數據框索引,我們可以像這樣使用reindex

# assign what we've done above to df_down
df_down = df.groupby(s).std().set_index(s.index[4::5])

df_up = df_down.reindex(range(20)).bfill()

好像:

           A         B
0   0.198019  0.320451
1   0.198019  0.320451
2   0.198019  0.320451
3   0.198019  0.320451
4   0.198019  0.320451
5   0.329750  0.408232
6   0.329750  0.408232
7   0.329750  0.408232
8   0.329750  0.408232
9   0.329750  0.408232
10  0.293297  0.223991
11  0.293297  0.223991
12  0.293297  0.223991
13  0.293297  0.223991
14  0.293297  0.223991
15  0.095633  0.376390
16  0.095633  0.376390
17  0.095633  0.376390
18  0.095633  0.376390
19  0.095633  0.376390

我們還可以使用其他東西來reindex ,例如range(0, 20, 2) reindex range(0, 20, 2)到樣本到偶數整數索引。

另外,這是可以做的一件事

def resample(df, rule, how=None, **kwargs):
    import pandas as pd
    if how==None:
        import numpy as np
        how = np.mean

    if isinstance(df.index, pd.DatetimeIndex) and isinstance(rule, str):
        return df.resample(rule, how, **kwargs)
    else:
        idx, bins = pd.cut(df.index, range(df.index[0], df.index[-1]+2, rule), right=False, retbins=True)
        aux = df.groupby(idx).apply(how)
        aux = aux.set_index(bins[:-1])
        return aux

@piSquared解決方案非常好,但我不喜歡在重新索引時選擇每手索引。

這對於每種下采樣(浮點索引)也應該有效,並自動選擇每個范圍中索引的均值:

df = pd.DataFrame(index = np.random.rand(20)*30, data=np.random.rand(20, 2), columns=['A', 'B'])
df.index.name = 'crazy_index'

s = (df.index.to_series() / 10).astype(int)

現在,您可以隨意選擇要在每個子組中計算的函數:

# calculate std() in each group
df.groupby(s).mean().set_index( s.groupby(s).apply(lambda x: np.mean(x.index)) )

                    A         B
crazy_index
3.667539     0.276986  0.317642
14.275074    0.248700  0.372551
25.054042    0.254860  0.297586

# calculate median() in each group
df.groupby(s).median().set_index( s.groupby(s).apply(lambda x: np.mean(x.index)) )
Out[38]:
                    A         B
crazy_index
3.667539     0.454654  0.521649
14.275074    0.451265  0.490125
25.054042    0.489326  0.622781

編輯:索引中存在一些錯誤,現在它是正確的和正常的。

暫無
暫無

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

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