簡體   English   中英

如何比較 python 中 dataframe 中每一行的所有值

[英]how to compare all values for each row in a dataframe in python

大家早上好,我的問題很簡單:

給定這樣的 dataframe:

import pandas as pd 
  
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
                    'b': [8, 18, 27, 20, 33, 49],
                    'c': [2, 24, 6, 16, 20, 52]})
print(df)

我想為每一行檢索最大值並將其與所有其他行進行比較。 如果差異大於 10,則創建另一個包含字符串“yes”或“not”的列

   a   b   c
0  1   8   2
1  2  18  24
2  3  27   6
3  4  20  16
4  5  33  20
5  6  49  52

我期待這樣的結果:

   a   b   c  res
0  1   8   2  not
1  2  18  24  not
2  3  27   6  yes
3  4  20  16  not
4  5  33  20  yes
5  6  49  52  not

非常感謝。

我想,下面的代碼可以提供幫助:

import pandas as pd

df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
                    'b': [8, 18, 27, 20, 33, 49],
                    'c': [2, 24, 6, 16, 20, 52]})

def find(x):
    if x > 10:
        return "yes"
    else:
        return "not"

df["diff"] = df.max(axis=1) - df.apply(lambda row: row.nlargest(2).values[-1],axis=1)
df["res"] = df["diff"].apply(find)
df.drop(columns="diff", axis=0, inplace=True)

Output: 在此處輸入圖像描述

這應該可以解決問題。

大約是這里提供的其他答案的兩倍到十倍

導入 pandas 作為 pd

df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
                   'b': [8, 18, 27, 20, 33, 49],
                   'c': [2, 24, 6, 16, 20, 52]})

df["res"] = df.apply(lambda row: "yes" if all(row.apply(lambda val: max(row) - val > 10 or val == max(row))) else "not", axis=1)

print(df)

結果

   a   b   c  res
0  1   8   2  not
1  2  18  24  not
2  3  27   6  yes
3  4  20  16  not
4  5  33  20  yes
5  6  49  52  not
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
                    'b': [8, 18, 27, 20, 33, 49],
                    'c': [2, 24, 6, 16, 20, 52]})

def _max(row):
    first, second = row.nlargest(2)
    if first - second > 10:
        return True
    else:
        return False

df["res"] = df.apply(_max, axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM