【问题标题】:Append values of a pandas data frame to a list by if condition通过 if 条件将 pandas 数据框的值附加到列表中
【发布时间】:2019-04-22 16:11:57
【问题描述】:

我有一个 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'的关键错误

【问题讨论】:

  • print (df.columns.tolist()) 是什么?
  • 结果是[0]。

标签: python pandas dataframe for-loop if-statement


【解决方案1】:

在我看来,不需要循环(慢),而且列名似乎是数字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]

【讨论】:

  • 您知道如何将零值附加到列表中以保持值的数量等于数据框吗?
  • @rude.boy - 一种可能的解决方案是excessLoad = [0] * (~mask).sum()
  • @rude.boy - 如果我的回答有帮助,请不要忘记accept。谢谢。
猜你喜欢
  • 2019-03-26
  • 2014-06-27
  • 2018-09-25
  • 1970-01-01
  • 2021-11-23
  • 2021-08-15
  • 2019-10-12
  • 2021-01-28
  • 2021-02-01
相关资源
最近更新 更多