簡體   English   中英

在熊貓中修復Groupby長度

[英]Fix Groupby Length in Pandas

我有一個按熊貓分組的數據框:

id    date    temperature
1  2011-9-12   12
   2011-9-18   12
   2011-9-19   12
2  2011-9-12   15
3  2011-9-12   15
   2011-9-16   15

在這里,每個id都有不同數量的溫度記錄。

我想修復它們,例如每個id的平均記錄數(例如3)。 如果缺少某些記錄,我想先放置零。

即我的最終數據幀應該是:

id    temperature
1     12
      12
      12
2     0
      0
      15
3     0
3     15
3     15

我需要將每個id的記錄數自定義為一些數字,也可以是每個id的平均記錄數。 如何獲得平均值?

只是用stackunstack

df.groupby(level=0)['temperature'].\
      apply(list).\
         apply(pd.Series).iloc[:,:3].\
                 apply(lambda x : pd.Series(sorted(x,key=pd.notnull)),1).\
                   fillna(0).stack().reset_index(level=0)
Out[523]: 
   id     0
0   1  12.0
1   1  12.0
2   1  12.0
0   2   0.0
1   2   0.0
2   2  15.0
0   3   0.0
1   3  15.0
2   3  15.0

Numpy解決方案可加快速度

s=df.groupby(level=0)['temperature'].apply(list)
s1=s.tolist()
arr = np.zeros((len(s1),3),int)
lens = [3-len(l) for l in s1]
mask = np.arange(3) >=np.array(lens)[:,None]
arr[mask] = np.concatenate(s1)
pd.DataFrame({'id':s.index.repeat(3),'temperature':arr.ravel()})

訪問groupby元素時,我們可以將reindexrange(3)一起使用。 之后,我們對sort_values並將NaN設置為第一個位置,以便可以將fillna為0。

df_new = pd.concat([
    d[['id', 'temperature']].reset_index(drop=True).reindex(range(3)).sort_values('id', na_position='first')
    for _, d in df.groupby('id')
], ignore_index=True)

df_new['id'].fillna(method='bfill', inplace=True)
df_new['temperature'].fillna(0, inplace=True)

print(df_new)
    id  temperature
0  1.0         12.0
1  1.0         12.0
2  1.0         12.0
3  2.0          0.0
4  2.0          0.0
5  2.0         15.0
6  3.0          0.0
7  3.0         15.0
8  3.0         15.0

注意,您將iddate作為索引,因此首先運行:

df.reset_index(inplace=True)

暫無
暫無

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

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