2024-10-01 22:30:30 发布
网友
我有两列包含一个DataFrame对象中的元组。在
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内并不重要
df
试试这个
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'
True
apply的输出:
apply
更有效的方法是将百分比提取到单独的列中,以便在比较中使用向量化方法:
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:
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)
试试这个
你可以这样做:
所以这里我们使用lambda来比较每一行的元组以生成一个布尔掩码,然后将它与^{} 一起使用,如果
True
则返回列a,否则返回列'b'
^{pr2}$apply
的输出:更有效的方法是将百分比提取到单独的列中,以便在比较中使用向量化方法:
您还可以定义一个自定义函数来处理动态数量的col并使用
max
:相关问题 更多 >
编程相关推荐