简体   繁体   中英

How do I subtract all the rows value in a particular column using Pandas library in Python?

Convert the NaN values to zero

Add a row called diff with the difference between minimum and maximum value in each column. Try solving it using lambda function

Add a column called diff with the difference between minimum and maximum value in each row.

The final df should look like df_final shown below

df = pd.DataFrame({'val1':[9,15,71,9,5], 'val2': [8,31,10, 14,np.nan]})
df

df_final = pd.DataFrame({'diff': {0: 1.0, 1: -16.0, 2: 61.0, 3: -5.0, 4: 5.0, 'diff': 35.0}, 'val1': {0: 9.0, 1: 15.0, 2: 71.0, 3: 9.0, 4: 5.0, 'diff': 66.0}, 'val2': {0: 8.0, 1: 31.0, 2: 10.0, 3: 14.0, 4: 0.0, 'diff': 31.0}})

df_final

Now I want to subtract all the rows value of column 'val1' and then 'val2' after which I have to create a new row below and show the result(the differences). (If possible,suggest me if I can do it using the lambda function)

IICU

df.fillna(0, inplace=True)#Replace NaN with zero
df['diff']=df.val1.sub(df.val2)#Subtract the two vals 
#df.loc[:,'diff']= df.apply(lambda x: x.max() - x.min(), axis=1)#if had more columns and needed differences between max and min across columns
df.loc['diff',:]= df.T.apply(lambda x: x.max() - x.min(), axis=1)#fifference between max and min in each column

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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