【问题标题】:Column arithmetic列算术
【发布时间】:2019-06-18 05:44:22
【问题描述】:

我遇到了一些代码问题。我有三列浮点数。我想添加三列,然后除以其中一列。

谢谢

我有以下代码:

df1 = pd.read_csv(file1)
cols = ['Opening Balance', 'Subscriptions/Redemptions', 'Gain (Loss)'] 
for col in cols:
    df1[col] = pd.to_numeric(df1[col], errors='coerce')
    num = ((df1['Opening Balance'] + df1['Subscriptions/Redemptions'] + df1['Gain (Loss)']))
    denom = df1['Opening Balance']
    performance = num/denom
df['new column'] = performance

我最终得到一个新列,不过是 NaN。

我希望得到一个浮动作为回报

【问题讨论】:

  • 欢迎来到stackoverflow!您能否提供一个可以与您的代码一起运行的示例数据集?
  • 检查 ***> here

标签: python pandas


【解决方案1】:

我认为您需要从 for 循环中删除 numdenom 部分。否则,它们每次都会被覆盖。更像是这样的:

df1 = pd.read_csv(file1)
cols = ['Opening Balance', 'Subscriptions/Redemptions', 'Gain (Loss)'] 
for col in cols:
    df1[col] = pd.to_numeric(df1[col], errors='coerce')

# escaped for loop here
# also removed parentheses
num = df1['Opening Balance'] + df1['Subscriptions/Redemptions'] + df1['Gain (Loss)']
denom = df1['Opening Balance']
performance = num/denom
df['new column'] = performance

每次您尝试将其中一列转换为数字时,它仅适用于该列。然后,当您尝试将其他“非数字”列与它相加时,您可能会得到NaN,因为它们尚未转换。完成循环中的转换,然后定义您的denomnum

另外,我认为您的 num 定义不需要括号

【讨论】:

  • 谢谢,效果很好,感谢您的帮助
  • @gaels67 很高兴它成功了。请考虑将答案标记为正确并尽可能投票。
猜你喜欢
  • 2022-01-06
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 2012-12-04
  • 2019-08-02
  • 2021-11-20
  • 2015-10-24
相关资源
最近更新 更多