简体   繁体   English

如何使用 Python 中的 Pandas 库减去特定列中的所有行值?

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

Convert the NaN values to zero将 NaN 值转换为零

Add a row called diff with the difference between minimum and maximum value in each column.添加一个名为 diff 的行,其中包含每列中最小值和最大值之间的差异。 Try solving it using lambda function尝试使用 lambda function 解决它

Add a column called diff with the difference between minimum and maximum value in each row.添加一个名为 diff 的列,其中包含每行中最小值和最大值之间的差异。

The final df should look like df_final shown below最终的 df 应该如下所示的df_final

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).现在我想减去列“val1”的所有行值,然后减去“val2”,之后我必须在下面创建一个新行并显示结果(差异)。 (If possible,suggest me if I can do it using the lambda function) (如果可能的话,建议我是否可以使用 lambda 函数来做到这一点)

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

在此处输入图像描述

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

相关问题 在 Pandas Dataframe 中查找相似的行并减去特定的列值 - Find similar rows and subtract a particular column value in Pandas Dataframe 如何在python中更新pandas数据框特定列的所有行? - How to update all rows in particular column of pandas dataframe in python? 我需要删除某一列中没有值或为“null”的所有行:使用 Python 和 Pandas - I need to drop all rows in a certain column where there is no value or is “null”: Using Python and Pandas 如何使用掩码变量将特定值分配给 pandas 中的列数据? - How do I assign a particular value to a column data in pandas using mask variable? 熊猫数据框找到具有特定列值的所有行? - pandas data frame find all rows with particular column value? 我如何 select 满足另一列 pandas 条件的最小值的所有行 - How do I select all rows with a minimum value that meet a condition in another column pandas 使用 pandas,如何检查列中是否存在特定序列? - Using pandas, how do I check if a particular sequence exist in a column? 如何使用python(pandas)更新csv文件中所有行的最后一列值 - How to update the last column value in all the rows in csv file using python(pandas) 如何根据Pandas中的匹配列减去行? - How to subtract rows based on matching column in Pandas? 如何按列的值对pandas数据帧的行进行分组? - How do I group the rows of a pandas data frame by a value of a column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM