Pandas dataframe:每批行的操作

Pandas dataframe : Operation per batch of rows

我有一个 pandas DataFrame df,我想为它计算每批行的一些统计数据。

例如,假设我有一个batch_size = 200000

对于每批 batch_size 行,我希望我的 DataFrame 的列 ID 具有唯一值的数量。

我该怎么做?

这是我想要的示例:

print(df)

>>
+-------+
|     ID|
+-------+
|      1|
|      1|
|      2|
|      2|
|      2|
|      3|
|      3|
|      3|
|      3|
+-------+

batch_size = 3

my_new_function(df,batch_size)

>>
For batch 1 (0 to 2) :
2 unique values 
1 appears 2 times
2 appears 1 time

For batch 2 (3 to 5) : 
2 unique values 
2 appears 2 times
3 appears 1 time

For batch 3 (6 to 8) 
1 unique values 
3 appears 3 times

注意:输出当然可以是一个简单的DataFrame

请参阅 拆分数据帧。 之后我会做:

from collections import Counter
Counter(batch_df['ID'].tolist())

请参阅 了解拆分过程,然后您可以这样做以获得唯一 'ID'

的数量
df = pd.DataFrame({'ID' : [1, 1, 2, 2, 2, 3, 3, 3, 3]})
batch_size = 3
result = []
for batch_number, batch_df in df.groupby(np.arange(len(df)) // batch_size):
    result.append(batch_df['ID'].nunique())
pd.DataFrame(result)

编辑:跟着user3426270的回答,我回答的时候没注意到

groupby 使用自定义聚合函数可能会解决您的问题

import pandas as pd
import numpy as np

df = pd.DataFrame({'ID':[1,1,2,2,2,3,3,3,3], 'X':1})

batch_size = 3
batches = np.ceil(df.shape[0]/batch_size)
df.index = pd.cut(df.index,batches,labels=range(batches))

###########

def myFunc(batch_data :pd.DataFrame):
    #print(batch_data.unique(),'\n')
    return batch_data.nunique()

output1 = df.groupby(df.index).aggregate({'ID':myFunc})
output2 = df.groupby(df.index).aggregate(myFunc)
output3 = df.groupby(df.index).aggregate({'ID':myFunc,'X':'std'})
# # 输出
#print(output1)
   ID
0   2
1   2
2   1

#print(output2)
   ID  X
0   2  1
1   2  1
2   1  1

#print(output3)
   ID    X
0   2  0.0
1   2  0.0
2   1  0.0