【问题标题】:Create column by adding columns using a condition通过使用条件添加列来创建列
【发布时间】:2019-03-14 15:16:16
【问题描述】:

我想在现有数据框中添加一个新列,我将在其中显示其他列中值的总和,但我不想包含我分配为变量的列名之一。

例如,

忽略 = 'Column3'

Column1 Column2 Column3
1        4       2
2        10      2
3        15      1

我想创建一个新列并只添加 Column1 和列但是正如你所看到的我有 ignore = 'Column3' 作为变量,有没有办法可以在代码中添加列但是合并变量 ignore这样忽略变量中使用的任何列都不会添加到计算中?

【问题讨论】:

  • 欢迎堆栈溢出。请提供一个示例输出以帮助澄清您的问题以及您迄今为止尝试过的内容。请参阅以下链接:minimal reproducible example

标签: python pandas variables add jupyter


【解决方案1】:

IIUC,你可以使用:

ignore='Column3'
df['New']=df.loc[:,df.columns!=ignore].sum(axis=1)
print(df)

   Column1  Column2  Column3  New
0        1        4        2    5
1        2       10        2   12
2        3       15        1   18

或者,如果您希望忽略列列表:

ignore=['Column3']
df['New']=df.loc[:,df.columns.difference(ignore)].sum(axis=1)
print(df)

   Column1  Column2  Column3  New
0        1        4        2    5
1        2       10        2   12
2        3       15        1   18

【讨论】:

  • 我试过了,但是不包括 column3 的列的总和不准确:(
  • @RSem 你能解释一下吗,总和就在你面前。 4+1 = 5。如果有任何其他逻辑,请解释,同时发布您想要的输出会帮助人们更加清晰。
猜你喜欢
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多