繁体   English   中英

仅当列值高于特定值时如何对列值进行数学运算,否则将其设置为1(以熊猫为单位)?

[英]How to do mathematical operations on the column values only if they are above certain values, otherwise set it to 1 in pandas?

我仅在“重量”列中的值大于0.25时,才尝试通过将0.25除以“重量”列来计算“因子”列,否则,我要将其设置为1。

我有以下数据框,其中“要素”列为预期输出:

                     Weight  Factor  
Date        Symbol              
1/1/2017    BTC       0.9    0.27                
            ETH       0.07   1                  
            XRP       0.03   1          
1/2/2017    BTC       0.8    0.31                
            ETH       0.07   1                   
            XRP       0.03   1          

这是我到目前为止的内容,但是我不能将其设置为1。

df['Factor'] = 0.25/df['Weight'].loc[df['Weight']>0.25]

一个快速的解决方案是一个应用。

df['Factor'] = df['Weight'].apply(lambda weight: 0.25 / weight if weight > 0.25 else 1)

在df ['weight']中的所有行上应用迭代,并将它们中的每一行用作执行操作的匿名lambda函数的输入。

另外,您也可以默认将Factor设置为1并接受您的代码。

df['Factor'] = 1
df['Factor'].loc[loc[df['Weight']>0.25]] = 0.25/df['Weight'].loc[df['Weight']>0.25]

编辑:现在缺少筛选器

df.loc[df['Weight'].notnull(), 'Factor'] = df['Weight'].loc[df['Weight'].notnull()].apply(lambda weight: 0.25 / weight if weight > 0.25 else 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM