Python Pandas比较数据帧元组值

2024-10-01 22:30:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两列包含一个DataFrame对象中的元组。在

 df    a                         b
      ('chicken wing', 1)        ('saucy', 0.35)
      ('burger', 0.85)           ('mason', 0.97)
      ('burping', 0.37)          ('lost in space', 0.47)
      ('marvelous', 1)           ('tremendous', .85)

我需要将包含更高数字的元组返回到新列。旧列是否保留在df内并不重要

结果

^{pr2}$

Tags: 对象indataframedfspacewing元组burger
3条回答

试试这个

def compare_tuples(row):
    if row['a'][1] >= row['b'][1]:
        return row['a']
    else:
        return row['b']
df['larger'] = df.apply(compare_tuples, axis=1)

你可以这样做:

In [1]: df['a'].where( df.apply(lambda row: row['a'][1] > row['b'][1], axis=1), df['b'])

Out [1]: 

0        (chicken wing, 1)
1            (mason, 0.97)
2    (lost in space, 0.47)
3           (marvelous, 1)
Name: a, dtype: object

所以这里我们使用lambda来比较每一行的元组以生成一个布尔掩码,然后将它与^{}一起使用,如果True则返回列a,否则返回列'b'

apply的输出:

^{pr2}$

更有效的方法是将百分比提取到单独的列中,以便在比较中使用向量化方法:

In[4]:
df['a_%'] = df['a'].apply(lambda x: x[1])
df['b_%'] = df['b'].apply(lambda x: x[1])
df

Out[4]: 
                   a                      b   a_%   b_%
0  (chicken wing, 1)          (saucy, 0.35)  1.00  0.35
1     (burger, 0.85)          (mason, 0.97)  0.85  0.97
2    (burping, 0.37)  (lost in space, 0.47)  0.37  0.47
3     (marvelous, 1)     (tremendous, 0.85)  1.00  0.85

In[5]:
df['max_value'] = df['a'].where(df['a_%'] > df['b_%'], df['b'])
df

Out[5]: 
                   a                      b   a_%   b_%              max_value
0  (chicken wing, 1)          (saucy, 0.35)  1.00  0.35      (chicken wing, 1)
1     (burger, 0.85)          (mason, 0.97)  0.85  0.97          (mason, 0.97)
2    (burping, 0.37)  (lost in space, 0.47)  0.37  0.47  (lost in space, 0.47)
3     (marvelous, 1)     (tremendous, 0.85)  1.00  0.85         (marvelous, 1)

您还可以定义一个自定义函数来处理动态数量的col并使用max

In[11]:
def func(x):
    vals = [y[1] for y in x]
    return x[vals.index(max(vals))]
df.apply(lambda row: func(row), axis=1)

Out[11]: 
0        (chicken wing, 1)
1            (mason, 0.97)
2    (lost in space, 0.47)
3           (marvelous, 1)
dtype: object
In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"a" : [('chicken wing', 1), ('burger', 0.85), ('burping', 0.37), ('marvelous', 1)], "b": [('saucy', 0.35), ('mason', 0.97), ('lost in space', 0.47), ('tremendous', .85)]})

In [3]: df['max_value'] = [a_value if (a_value[1] > b_value[1]) else b_value for a_value, b_value in zip(df.a, df.b)]

In [4]: df
Out[4]: 
                   a                      b              max_value
0  (chicken wing, 1)          (saucy, 0.35)      (chicken wing, 1)
1     (burger, 0.85)          (mason, 0.97)          (mason, 0.97)
2    (burping, 0.37)  (lost in space, 0.47)  (lost in space, 0.47)
3     (marvelous, 1)     (tremendous, 0.85)         (marvelous, 1)

相关问题 更多 >

    热门问题