使用多列的Pandas数据框列表理解的内存有效方式 [英] Memory efficient way for list comprehension of pandas dataframe using multiple columns

查看:38
本文介绍了使用多列的Pandas数据框列表理解的内存有效方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列表理解中的熊猫数据框的行上运行一个函数.数据框可以具有不同数量的列.如何利用数据框的这些列?

I want to run a function on rows of a pandas dataframe in list comprehension. Dataframe can have varying number of columns. How to make use these columns of dataframe?

import  pandas as pd

df = {'chrom': ['chr1', 'chr1','chr1'], 'start': [10000, 10100, 12000], 'end':[10150,10120,12250], 'S1':[1, 1, 1],'S2':[2, 2, 2],'S3':[3, 3, 3] }
df = pd.DataFrame(data=df)
print(df)

def func(row):
    print(row)


[func(row) for row in zip(df['chrom'],df['start'],df['S1'],df['S2'],df['S3'])]

如何以内存有效的方式执行此操作?这样我们就不会在大数据帧中出现任何内存错误.

How to do this in a memory efficient way? So that we do not get any memory error for big dataframes.

推荐答案

感谢您的回答.

同时,我发现了以下解决方案:

Meantime, I found the following as a solution:

df_columns = list(df.columns.values)
[func_using_list_comp(
                row,
                var1,
                var2,
                var3,
                ...,
                df_columns) for row in df[df_columns].values]

通过这种方式,我不需要使用zip函数并使它可用于任意数量的列.

In this way, I did not need to use zip function and make it work for any number of columns.

我希望这也可以提高内存效率.顺便说一句,每次处理一行时,我都会在var1,var2,var3中进行累积.

I hope this is also memory efficient. By the way, I'm accumulating in the var1, var2, var3 each time I process a row.

如果我使用生成器而不是列表,它将对我的内存使用产生多大影响,并且在处理完所有行之后是否将获得所有累积的数据?

If I use generator instead of a list, how much will it affect my memory usage and will I get the all the accumulated data after processing all rows?

因为,在处理完所有行之后,我将返回这些var1,var2,var3.

Since, I'm returning these var1, var2, var3 after all rows are processed.

这篇关于使用多列的Pandas数据框列表理解的内存有效方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆