简体   繁体   English

pandas:减去两列并将结果保存为绝对值

[英]pandas: subtracting two columns and saving result as an absolute

I have the code where I have a csv file opened in pandas and a new one I'm creating. 我有代码,我在pandas中打开了一个csv文件,我正在创建一个新的。 There's a row I need to create "two last lines commented out" of an absolute value of subtracting two rows. 有一行我需要创建一个“减去两行的绝对值”的“最后两行注释掉”。 I've tried a number of ideas in my head all bring an error. 我在脑海里尝试了很多想法都带来了错误。

import pandas as pd
import numpy as np

df = pd.read_csv(filename_read)
ids = df['id']

oosDF = pd.DataFrame()
oosDF['id'] = ids
oosDF['pred'] = pred
oosDF['y'] = df['target']
#oosDF['diff'] = oosdF['pred'] - oosDF['y']
#oosDF['diff'] = oosDF.abs()

I think you need for new DataFrame by subset (columns names in double [] ) and then get abs value of difference of columns: 我认为您需要通过子集(double []列名称)获取新的DataFrame ,然后获取列的差异的abs值:

oosDF = df[['id','pred', 'target']].replace(columns={'target':'y'})
oosDF['diff'] = (oosDF['pred'] - oosDF['y']).abs()

In your first commented line, you have oosdF instead of oosDF . 在您的第一个注释行中,您有oosdF而不是oosDF

In your second commented line, you're setting the column to be abs() applied to the whole dataframe. 在第二个注释行中,您将列设置为abs()应用于整个数据帧。 That should be oosDF['diff'].abs() 那应该是oosDF['diff'].abs()

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM