在Pandas中仅获取少数元素

2024-05-20 11:11:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个按熊猫分组的数据帧:

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

在这里,每个id有不同数量的温度记录。你知道吗

我想修复它们,比如说每个id的平均记录数(比如3个)。如果一些记录丢失了,我想在开始的时候放零。你知道吗

我想保留最近的记录。

也就是说,我的最终数据帧应该是:

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

以下是给出第行错误的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) ## Error
    pd.DataFrame({'id':s.index.repeat(3),'temperature':arr.ravel()})

我怀疑这个错误是因为我的数据可以有超过3行的id

如何解决这个问题?你知道吗


Tags: 数据numpyid数量datelen错误np
2条回答

有点冗长的解决方案,但很有效:

df.groupby('id').apply(lambda x: x.sort_values(by='date'))
                .drop('id', axis=1)['temperature'].groupby(level=0).tail(3)
                .groupby(level=0).apply(lambda x: np.pad(x, (3-len(x),0), 'constant'))
                .reset_index()

   id   temperature
0   1  [20, 12, 90]
1   2    [0, 0, 15]
2   3   [0, 15, 15]

使用^{}ascending=False作为计数器,使用^{}^{}创建的MultiIndex

print (df)
   id       date  temperature
0   1  2011-9-12           12
1   1  2011-9-12           20
2   1  2011-9-18           12
3   1  2011-9-19           90
4   2  2011-9-12           15
5   3  2011-9-12           15
6   3  2011-9-16           15

N = 3
df['new'] = df.groupby('id').cumcount(ascending=False)
mux = pd.MultiIndex.from_product([df['id'].unique(), range(N-1, -1, -1)], names=['id','new'])
df1 = (df.set_index(['id', 'new'])['temperature']
        .reindex(mux, fill_value=0)
        .reset_index(level=1, drop=True)
        .reset_index())

print (df1)
   id  temperature
0   1           20
1   1           12
2   1           90
3   2            0
4   2            0
5   2           15
6   3            0
7   3           15
8   3           15

编辑:

如果多索引DataFrame

print (df)
              temperature
id date                  
1  2011-9-12           12
   2011-9-12           20
   2011-9-18           12
   2011-9-19           90
2  2011-9-12           15
3  2011-9-12           15
   2011-9-16           15

print (df.index)
MultiIndex(levels=[[1, 2, 3], ['2011-9-12', '2011-9-16', '2011-9-18', '2011-9-19']],
           codes=[[0, 0, 0, 0, 1, 2, 2], [0, 0, 2, 3, 0, 0, 1]],
           names=['id', 'date'])

N = 3
df['new'] = df.groupby('id').cumcount(ascending=False)
mux = pd.MultiIndex.from_product([df.index.levels[0], range(N-1, -1, -1)], names=['id','new'])
df1 = (df.reset_index(level=1, drop=True)
         .set_index('new', append=True)['temperature']
         .reindex(mux, fill_value=0)
         .reset_index(level=1, drop=True)
         .reset_index())

print (df1)
   id  temperature
0   1           20
1   1           12
2   1           90
3   2            0
4   2            0
5   2           15
6   3            0
7   3           15
8   3           15

相关问题 更多 >