Skip to main content
 首页 » 编程设计

python之通过 if 条件将 pandas 数据框的值附加到列表

2024年12月31日9del

我有一个 pandas df,其中有一列具有正浮点值或负浮点值:

snapshot                        0 (column name) 
2018-06-21 00:00:00        -60.18 
2018-06-21 00:00:15         43.78 
2018-06-21 00:00:30        -22.08 

现在我想将正值附加到名为的列表中:

excessSupply=[] 

负值:

excessLoad=[] 

通过

        for row in self.dfenergyBalance: 
 
        if self.dfenergyBalance['0'] < 0: 
 
            self.excessLoad.append(self.dfenergyBalance['0']) 
 
        else: 
 
            self.excessLoad.append(0) 

(excessSupply 是 if 条件 self.dfenergyBalance > 0)

结果是列名'0'的键错误

请您参考如下方法:

在我看来没有循环(慢)是必要的,而且列名似乎是数字0:

mask = dfenergyBalance[0] < 0 
 
excessSupply = dfenergyBalance.loc[mask, 0].tolist() 
excessLoad = dfenergyBalance.loc[~mask, 0].tolist() 
 
print (excessSupply) 
[-60.18, -22.08] 
 
print (excessLoad) 
[43.78] 

编辑:

对于正值长度只有 0 的列表:

excessLoad = [0] * (~mask).sum() 
print (excessLoad) 
[0] 

如果只需要一个列表将正值替换为 0 值:

L = np.where(mask, dfenergyBalance[0], 0).tolist() 
print (L) 
[-60.18, 0.0, -22.08]