python - Pandas 数据帧 : Operation per batch of rows

标签 python pandas performance batch-processing

我有一个 Pandas 数据帧 df我想为每批行计算一些统计信息。

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

每批batch_size行 我​​想要列的唯一值数量 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

最佳答案

this post对于拆分过程,您可以这样做以获得唯一“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的回答,我回答的时候没注意到

关于python - Pandas 数据帧 : Operation per batch of rows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56218003/

相关文章:

performance - 为什么 `filterM + mapM_`比 `mapM_ + when`慢得多,且列表很大?

c# - 有没有非常快速的校验和生成算法?

python - 加权平均日期时间,关闭但仅限某些月份

sql - Mysql NOT IN运算符对于大结果集的性能问题?

python - XLRDError : Unsupported format, 或损坏的文件:预期的 BOF 记录;

python - pandas DataFrame 中列的更短符号

python - 根据单独系列中的条件更新 Pandas 系列

python - Pandas 0.19.2 read_excel IndexError : List index out of range

python - Matplotlib/Imshow/透明层无处不在但某些点

python - 为 Celery 中的任务类指定队列