首页 > 解决方案 > 找到一种方法来有效地执行 DataFrame 的某些列的计算

问题描述

我正在尝试查看 Pandas DataFrame 的特定列并尝试执行以下操作:

col0 col1   col2
int0 float0 str0
int1 float1 str0
int2 float2 str1

我试图在该列上逐行迭代 DataFrame,但这似乎效率不高。 Lambda 是一种选择,但我不确定 DataFrame 列是否有类似“列表理解”的东西(据我所知,这是熊猫系列)。

如果,假设 DataFrame 被定义为 df,那么我想做一些事情,比如:

for row in df:
    if df['col2'] == str0:
        # do some calculation for all str0 types
    elif df['col2'] == str1:
        # do another calculation for all str1 types
    else:
        # do another calculation for all other types (which are actually str2 types implied by the if-elif-else statement)

我试图重复此操作以获得一个单独的 NumPy 矩阵,该矩阵将创建一个与 DataFrame 的相应行相对应的 NumPy 行。通过检查“col2”的条件,将根据其值执行单独的计算,并生成相应 NumPy 数组的行。

请让我知道是否有有效的方法(在规范、Pythonic 编码以及时间和内存效率方面)!所有帮助将不胜感激。

标签: pythonpandasnumpydataframe

解决方案


这更像是一个np.select问题

condition = [df['col2'] == str0, df['col2'] == str1...]
Target = [function1 , function2...]

df['NewCol'] = np.select(condition , Target , default = np.nan )

推荐阅读