簡體   English   中英

Pandas dataframe,在一行中,查找所選列中的最大值,並根據該值查找另一列的值

[英]Pandas dataframe, in a row, to find the max in selected column, and find value of another column based on that

我有一個這樣的 dataframe:

import pandas as pd
df = pd.DataFrame({'x1':[20,25],'y1':[5,8],'x2':[22,27],'y2':[10,2]})

去向

       x1  y1  x2  y2
    0  20   5  22  10
    1  25   8  27   2

X 和 Y 配對在一起。 我需要比較 y1 和 y2 並在每一行中獲得最大值。 並找到對應的x。 因此第[0]行的最大值是y2(=10),對應的x是x2(=22)。 第二行將是 y1 (=8) 和 x1(=25)。 預期結果,新列 x 和 y:

   x1  y1  x2  y2   x   y
0  20   5  22  10  22  10
1  25   8  27   2  25   8

這是一個簡單的 dataframe 我為了詳細說明這個問題。 X 和 Y 對,在我的例子中,可以是 30 對。

# get a hold on "y*" columns
y_cols = df.filter(like="y")

# get the maximal y-values' suffixes, and then add from front "x" to them
max_x_vals = y_cols.idxmax(axis=1).str.extract(r"(\d+)$", expand=False).radd("x")
# get the locations of those x* values
max_x_ids = df.columns.get_indexer(max_x_vals)

# now we have the indexes of x*'s in the columns; NumPy's indexing
# helps to get a cross section
df["max_xs"] = df.to_numpy()[np.arange(len(df)), max_x_ids]

# for y*'s, it's directly the maximum per row
df["max_ys"] = y_cols.max(axis=1)

要得到

>>> df

   x1  y1  x2  y2  max_xs  max_ys
0  20   5  22  10      22      10
1  25   8  27   2      25       8

您可以在申請 function 的幫助下完成。

import pandas as pd
import numpy as np

df = pd.DataFrame({'x1':[20,25],'y1':[5,8],'x2':[22,27],'y2':[10,2]})
y_cols = [col for col in df.columns if col[0] == 'y'] 
x_cols = [col for col in df.columns if col[0] == 'x'] 

def find_corresponding_x(row):
    max_y_index = np.argmax(row[y_cols])
    return row[f'{x_cols[max_y_index]}']

df['corresponding_x'] = df.apply(find_corresponding_x, axis = 1)

這是一個解決方案:

a = df[df['y1'] < df['y2']].drop(columns=['y1','x1']).rename(columns={'y2':'y', 'x2':'x'})
b = df[df['y1'] >= df['y2']].drop(columns=['y2','x2']).rename(columns={'y1':'y', 'x1':'x'})

result = pd.concat([a,b])

如果您需要保持順序,則可以添加另一列具有原始索引並在連接后按它排序

您可以使用下面的 function。 請記住像我在此代碼中所做的那樣導入 pandas 和 numpy。 導入您的數據集並使用Max_number function。

import pandas as pd
import numpy as np
df = pd.DataFrame({'x1':[20,25],'y1':[5,8],'x2':[22,27],'y2':[10,2]})

def Max_number (df):
    columns = list(df.columns)
    rows = df.shape[0]
    max_value = []
    column_name = []

    for i in range(rows):
        row_array = list(np.array(df[i:i+1])[0])
        maximum = max(row_array)
        max_value.append(maximum)
        index=row_array.index(maximum)
        column_name.append(columns[index])
    
    return pd.DataFrame({"column":column_name,"max_value":max_value})

返回這個:

行索引 柱子 最大值
0 x2 22
1個 x2 27

如果先是 x1 列,然后是 y1,然后是 x2、y2 等等,您可以嘗試:

a = df.columns.get_indexer(y_cols.idxmax(axis=1))
df[['y', 'x']] = df.to_numpy()[np.arange(len(df)), [a, a - 1]].T

我希望它適用於您的解決方案,

import pandas as pd
df = pd.DataFrame({'x1':[20,25],'y1':[5,8],'x2':[22,27],'y2':[10,2]})
df['x_max'] = df[['x1', 'x2']].max(axis=1)
df['y_max'] = df[['y1', 'y2']].max(axis=1)
df

暫無
暫無

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

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