简体   繁体   English

减去数据帧中的两个值

[英]subtract two values in dataframe

I have a dataframe (df) that has 2 columns by the name [1,2], I used the following code to add 2 more columns: largest and second largest that display at each row which is the highest number and the second highest.我有一个数据框 (df),它有 2 列,名称为 [1,2],我使用以下代码添加了另外 2 列:最大和第二大的列,显示在每一行的最高数字和第二大数字。

    df = RSRP_per_sec(2)
    df2=df.copy()
    df2['highest']=0
    df2['second_highest']=0
    for i in range(len(df)):
        l=sorted([(x, df.iloc[i][x]) for x in df.columns], key=lambda y: y[1])
        df2['highest'].iloc[i]=l[-1][0]
        df2['second_highest'].iloc[i]=l[-2][0]

and now df dataframe is like this where the columns are ['1','2','highest','second_highest'] and displaying the first row:现在 df 数据框是这样的,其中列是 ['1','2','highest','second_highest'] 并显示第一行:

1        2       highest    second_highest

-86     -102      1           2

Now I would like to add one more column that calculates the difference between the highest and second highest by checking at each row which column is the highest and which is the second and subtract them from each others.现在我想再添加一列,通过检查每一行哪一列是最高的,哪一列是第二列,并从彼此中减去它们来计算最高和第二高之间的差异。

Note: for my case now its easy as there are only 2 columns to subtract but I would like to expand the number of columns that highest and second highest columns will have a different values.注意:对于我的情况,现在很容易,因为只有 2 列要减去,但我想扩展最高和第二高列将具有不同值的列数。

Take the column values and use them to index the corresponding columns:获取列值并使用它们来索引相应的列:

df["diff_highest"] = df[str(df["highest"].values[0])] - df[str(df["second_highest"].values[0])]

Btw you can also get the two highest values by using .sort_values() to each row:顺便说一句,您还可以通过对每一行使用 .sort_values() 来获得两个最高值:

df["1"] = [-86]
df["2"] = [-102]
df["3"] = [12]
df["highest"] = [None]
df["second_highest"] = [None]

df.iloc[0].sort_values(ascending=False).dropna().index[:2]

outputs产出

Index(['3', '1'], dtype='object')

I would suggest to set "highest" and "second_highest" to None so it does not conflict the sorting.我建议将“highest”和“second_highest”设置为 None ,这样它就不会与排序冲突。

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

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