我有一个熊猫数据帧,有两个固定的列,在这两个列之后有一个可变的列数。我需要根据其他列的值来更改第二列中的值。问题是,我不知道我的数据帧中会有多少额外的列,我需要设置一种灵活的方法来检查它们的值。你知道吗
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。你知道吗
我遇到了麻烦,因为我无法创建特定的条件,因为我事先不知道附加列的编号和名称。我尝试使用位置索引,因为它们都将在第二个之后,但不起作用。有办法吗?你知道吗
下面是一个使用^{} 和^{} 而不使用
apply
的解决方案:结果:
您可以按照下面的方法对所有行使用apply function。你知道吗
首先定义一个函数,查看行中是否至少有一个值与零不同:
然后可以对前两列之后的所有列使用apply函数,并将结果放入
TRADING_DAY
列,如下所示:相关问题 更多 >
编程相关推荐