大熊猫,groupby后数据为空时保留列?

时间:2019-03-21 08:10:43

标签: python pandas

(Pdb) df.head()
Empty DataFrame
Columns: [user_id, review_meta_id, rating_type, score, timestamp, user_id_index, review_meta_id_index]
Index: []

(Pdb) df.groupby(['user_id'], as_index=False).apply(lambda grp: grp.nlargest(M, 'timestamp'))
Empty DataFrame
Columns: []
Index: []

我可以让第二个创建一个空的数据框,但其列与第一个输出中的列相同吗?
(主要是在两种情况下都保持相同的界面)

我想要类似以下的内容...

(Pdb) df.groupby(['user_id'], as_index=False).apply(lambda grp: grp.nlargest(M, 'timestamp'))
 Empty DataFrame
Columns: [user_id, review_meta_id, rating_type, score, timestamp, user_id_index, review_meta_id_index]
Index: []

1 个答案:

答案 0 :(得分:0)

您可以对DataFrame.sort_valuesGroupBy.head使用更快的替代解决方案:

M = 3
df = pd.DataFrame({'user_id':[1] * 5 + [2] * 4,
                   'timestamp':range(9)})
print (df)
   user_id  timestamp
0        1          0
1        1          1
2        1          2
3        1          3
4        1          4
5        2          5
6        2          6
7        2          7
8        2          8

print (df.sort_values(['user_id','timestamp'], ascending=[True, False])
         .groupby('user_id')
         .head(M))

   user_id  timestamp
4        1          4
3        1          3
2        1          2
8        2          8
7        2          7
6        2          6

df = pd.DataFrame(columns=['user_id','timestamp'])
print (df)
Empty DataFrame
Columns: [user_id, timestamp]
Index: []

print (df.sort_values(['user_id','timestamp'], ascending=[True, False])
         .groupby('user_id')
         .head(M))
Empty DataFrame
Columns: [user_id, timestamp]
Index: []