[英]Iterating through columns in a dataframe to add to a Total Value column in Python pandas
I am trying to iterate through some column names to add up the total value in a 'TotalValue' column.我正在尝试遍历某些列名以将“TotalValue”列中的总值相加。 I get:我得到:
KeyError: 'TotalValue'
I have shown what the equation would look like if I typed it out to get the total.我已经展示了如果我输入它来得到总数的等式会是什么样子。
df['TotalValueByHand'] = df['Value_SCHD'] + df['Value_VBR'] + df['Value_IXUS'] + df['Value_MDIZX']
I would like to iterate through columns though because ultimately I plan to have a lot more in the list.不过,我想遍历列,因为最终我计划在列表中添加更多内容。 Sorry if the indentation comes out weird, it looked okay when I typed it.抱歉,如果缩进很奇怪,我输入时看起来还不错。
stockList = ["SCHD", "VBR", "MDIZX", "IXUS"]
for s in stockList:
df['TotalValue'] = np.where(df['Value_' + s] > 0, df['TotalValue'] + df['Value_' + s], df['TotalValue'])
If need sum
only values greater like 0
use list comprehension for generate all columns names with DataFrame.clip
and sum
:如果只需要sum
大于0
的值,请使用列表理解生成所有列名称,并使用DataFrame.clip
和sum
:
stockList = ["SCHD", "VBR", "MDIZX", "IXUS"]
cols = [f'Value_{s}' for s in stockList]
df['TotalValue'] = df[cols].clip(lower=0).sum(axis=1)
If need only sum
:如果只需要sum
:
cols = [f'Value_{s}' for s in stockList]
df['TotalValue'] = df[cols].sum(axis=1)
Your solution is possible if create first column filled by 0
:如果创建由0
填充的第一列,您的解决方案是可能的:
df['TotalValue'] = 0
for s in stockList:
df['TotalValue'] = np.where(df['Value_' + s] > 0, df['TotalValue'] + df['Value_' + s], df['TotalValue'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.