简体   繁体   English

Pandas:在列的每一行中查找最大值,并在另一列中标识相应的值

[英]Pandas: Find max value in each row of a column and identify corresponding values in another column

I have a two pandas data frame columns, for which the values are lists of tuples such as: 我有两个pandas数据框列,其值是元组列表,如:

df[‘A’].values
(1.55, 2.07, 2.20, 2.23)
(0.67, 1.10, 1.73, 1.35)
(2.92, 1.98, 2.30, 2.66)

and

df[‘B’].values
(1.55, 0.0086, 0.078, 0.12)
(0.672, 0.142, 0.0166, 0.0173)
(1.97, 0.0094, 0.1648, 0.016)

I would like to pick the largest value for each row of df['A'] and find the value in the corresponding position of df['B'] to generate a new column such as: 我想为df['A']每一行选择最大值,并在df['B']的相应位置找到该值以生成新列,例如:

> df[‘C’]
0.12
0.0166
1.97
import pandas as pd
import numpy as np


df_dict = dict(A=[(1.55, 2.07, 2.20, 2.23), (0.67, 1.10, 1.73, 1.35), (2.92, 1.98, 2.30, 2.66)],
    B=[(1.55, 0.0086, 0.078, 0.12), (0.672, 0.142, 0.0166, 0.0173), (1.97, 0.0094, 0.1648, 0.016)])

df = pd.DataFrame(df_dict)

Out[180]: 
                         A                               B
0  (1.55, 2.07, 2.2, 2.23)     (1.55, 0.0086, 0.078, 0.12)
1  (0.67, 1.1, 1.73, 1.35)  (0.672, 0.142, 0.0166, 0.0173)
2  (2.92, 1.98, 2.3, 2.66)   (1.97, 0.0094, 0.1648, 0.016)

def apply_func(row):
    return row.B[np.array(row.A).argmax()]

df['C'] = df.apply(apply_func, axis=1)

Out[182]: 
                         A                               B       C
0  (1.55, 2.07, 2.2, 2.23)     (1.55, 0.0086, 0.078, 0.12)  0.1200
1  (0.67, 1.1, 1.73, 1.35)  (0.672, 0.142, 0.0166, 0.0173)  0.0166
2  (2.92, 1.98, 2.3, 2.66)   (1.97, 0.0094, 0.1648, 0.016)  1.9700

暂无
暂无

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

相关问题 使用 Pandas 查找列的最大值并返回相应的行值 - Find maximum value of a column and return the corresponding row values using Pandas Python pandas dataframe:为另一列的每个唯一值查找最大值 - Python pandas dataframe: find max for each unique values of an another column 如何获取熊猫数据框列的最大值并在另一列中找到相应的值? - How do I take max value of a pandas dataframe column and find the corresponding value in another column? Pandas Dataframe:groupby id查找最大列值并返回另一列的对应值 - Pandas Dataframe: groupby id to find max column value and return corresponding value of another column 熊猫:每行中最多3列值的总和 - Pandas: Sum of the Max 3 Column Values in Each Row 使用 Pandas 查找特定列的“最大值”,然后使用同一行中的相应 ITEM 输出该 VALUE - Find the 'max' of a specific column with Pandas, then output that VALUE with a corresponding ITEM from the same row 熊猫idxmax()获取与行中最大值对应的列名 - Pandas idxmax() get column name corresponding to max value in row 熊猫:查找列名和值,每一行的最大值(和第二最大值) - Pandas: find column name and value with max (and second max) value for each row 给定月份的列及其对应的值,如何找到每年的最大值? - given column of month and its corresponding values, How to find max value in each year? Pandas dataframe,在一行中,查找所选列中的最大值,并根据该值查找另一列的值 - Pandas dataframe, in a row, to find the max in selected column, and find value of another column based on that
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM