可变列数上的多个条件

2024-10-01 19:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧,有两个固定的列,在这两个列之后有一个可变的列数。我需要根据其他列的值来更改第二列中的值。问题是,我不知道我的数据帧中会有多少额外的列,我需要设置一种灵活的方法来检查它们的值。你知道吗

def validateAndSetSignals(self, signalsDf, datesReb):


        totSignals = pd.DataFrame(0, columns = ['TOT_SIGNAL','TRADING_DAY'], index = self.unqDates)
        for names in signalsDf.keys():
            tmpSign = signalsDf[names].sum(axis =1)
            totSignals[names] = tmpSign
            totSignals['TOT_SIGNAL'] = totSignals['TOT_SIGNAL'] + tmpSign




        for i in range (len(totSignals.columns) - 2):         
            totSignals.loc[totSignals[totSignals.columns[2:]] != 0, 'TRADING_DAY'] = 1

如您所见,'TOT_SIGNAL''TRADING_DAY'是固定的列,而我可能有一个或多个列,这取决于开始时的for循环。然后我想检查是否至少有一个附加列与0不同,并将列'TRADING_DAY'设置为1。你知道吗

我遇到了麻烦,因为我无法创建特定的条件,因为我事先不知道附加列的编号和名称。我尝试使用位置索引,因为它们都将在第二个之后,但不起作用。有办法吗?你知道吗


Tags: columns数据方法inselfforsignalnames
2条回答

下面是一个使用^{}^{}而不使用apply的解决方案:

df = pd.DataFrame(index=range(8), columns = ['TOT_SIGNAL','TRADING_DAY']).join(pd.DataFrame(np.eye(8, 5)))

df.TRADING_DAY = df.TRADING_DAY.mask((df.iloc[:,2:] != 0).any(axis=1), 1)

结果:

  TOT_SIGNAL TRADING_DAY    0    1    2    3    4
0        NaN           1  1.0  0.0  0.0  0.0  0.0
1        NaN           1  0.0  1.0  0.0  0.0  0.0
2        NaN           1  0.0  0.0  1.0  0.0  0.0
3        NaN           1  0.0  0.0  0.0  1.0  0.0
4        NaN           1  0.0  0.0  0.0  0.0  1.0
5        NaN         NaN  0.0  0.0  0.0  0.0  0.0
6        NaN         NaN  0.0  0.0  0.0  0.0  0.0
7        NaN         NaN  0.0  0.0  0.0  0.0  0.0

您可以按照下面的方法对所有行使用apply function。你知道吗

首先定义一个函数,查看行中是否至少有一个值与零不同:

def checkRow(row):
    for x in row:
        # Equivalent to if x != 0 or if x == True
        if x:
            return 1
    # If all columns for this row is equal to 0 return 0
    return 0

然后可以对前两列之后的所有列使用apply函数,并将结果放入TRADING_DAY列,如下所示:

totSignals.TRADING_DAY = totSignals.iloc[:, 2:].apply(lambda row: checkRow(row), axis=1)

To understand better the code, here is the offical documentation of all the function used:

DataFrame.iloc: to select the columns that you are interested in.

DataFrame.apply: to apply the function on every row of the DataFrame object.

相关问题 更多 >

    热门问题