【问题标题】:Applying function to each row of pandas data frame - with speed将功能应用于熊猫数据框的每一行 - 快速
【发布时间】:2015-01-23 03:49:23
【问题描述】:

我有一个具有以下基本结构的数据框:

import numpy as np
import pandas as pd
tempDF = pd.DataFrame({'condition':[0,0,0,0,0,1,1,1,1,1],'x1':[1.2,-2.3,-2.1,2.4,-4.3,2.1,-3.4,-4.1,3.2,-3.3],'y1':[6.5,-7.6,-3.4,-5.3,7.6,5.2,-4.1,-3.3,-5.7,5.3],'decision':[np.nan]*10})
print tempDF
   condition  decision   x1   y1
0          0       NaN  1.2  6.5
1          0       NaN -2.3 -7.6
2          0       NaN -2.1 -3.4
3          0       NaN  2.4 -5.3
4          0       NaN -4.3  7.6
5          1       NaN  2.1  5.2
6          1       NaN -3.4 -4.1
7          1       NaN -4.1 -3.3
8          1       NaN  3.2 -5.7
9          1       NaN -3.3  5.3

在每一行中,如果“条件”列为零并且“x1”和“y1”的符号相同(正或负),我想将“决策”列的值更改为零 -就本脚本而言,零被认为是正数。如果“x1”和“y1”的符号不同,或者“条件”列等于 1(不管“x1”和“y1”的符号如何),那么“决策”列应该等于 1。我希望我已经解释清楚了。

我可以按如下方式遍历数据框的每一行:

for i in range(len(tempDF)):
    if (tempDF.ix[i,'condition'] == 0 and ((tempDF.ix[i,'x1'] >= 0) and (tempDF.ix[i,'y1'] >=0)) or ((tempDF.ix[i,'x1'] < 0) and (tempDF.ix[i,'y1'] < 0))):
        tempDF.ix[i,'decision'] = 0
    else:
        tempDF.ix[i,'decision'] = 1

print tempDF
           condition  decision   x1   y1
        0          0         0  1.2  6.5
        1          0         0 -2.3 -7.6
        2          0         0 -2.1 -3.4
        3          0         1  2.4 -5.3
        4          0         1 -4.3  7.6
        5          1         1  2.1  5.2
        6          1         1 -3.4 -4.1
        7          1         1 -4.1 -3.3
        8          1         1  3.2 -5.7
        9          1         1 -3.3  5.3

这会产生正确的输出,但速度有点慢。我拥有的真实数据框非常大,需要多次进行这些比较。有没有更有效的方法来达到预期的效果?

【问题讨论】:

    标签: python numpy pandas dataframe


    【解决方案1】:

    首先,使用np.sign 和比较运算符创建一个布尔数组True,其中决定应为1

    decision = df["condition"] | (np.sign(df["x1"]) != np.sign(df["y1"]))
    

    这里我使用了德摩根定律。

    然后将其转换为int 并放入数据框中:

    df["decision"] = decision.astype(int)
    

    给予:

    >>> df
       condition  decision   x1   y1
    0          0         0  1.2  6.5
    1          0         0 -2.3 -7.6
    2          0         0 -2.1 -3.4
    3          0         1  2.4 -5.3
    4          0         1 -4.3  7.6
    5          1         1  2.1  5.2
    6          1         1 -3.4 -4.1
    7          1         1 -4.1 -3.3
    8          1         1  3.2 -5.7
    9          1         1 -3.3  5.3
    

    【讨论】:

    • 非常小的一点——我可能会使用 np.signbit() 代替,这样零值将包含在正值中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2015-09-30
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多