问题描述
我的数据集如下所示
id tre f1 f2 f3 t1
1 2 0 1 1 er
2 3 1 0 0 po
3 abc 1 1 1 oo
4 yt 0 0 0 pp
我需要专注于f1,f2,f3。 创建基于f1,f2,f3的新col ....新col中的值将为max(f1,f2,f3) 我应该使用什么功能
答案 0 :(得分:1)
df['max'] = df.apply(lambda x : max(x['f1'], x['f2'], x['f3']), axis = 1)
答案 1 :(得分:1)
只需使用pd.DataFrame.max
# test data
from io import StringIO
data = StringIO('''id,tre,f1,f2,f3,t1
1,2,0,1,1,er
2,3,1,0,0,po
3,abc,1,1,1,oo
4,yt,0,0,0,pp''')
df = pd.read_csv(data)
df['maxf'] = df[['f1', 'f2', 'f3']].max(axis=1)
output:
id tre f1 f2 f3 t1 maxf
0 1 2 0 1 1 er 1
1 2 3 1 0 0 po 1
2 3 abc 1 1 1 oo 1
3 4 yt 0 0 0 pp 0
已编辑:查找以'f'
开头的所有列的最大值:
cols = list(filter(lambda x: x.startswith('f'), df.columns))
df['maxf'] = df[cols].max(axis=1)
答案 2 :(得分:0)
这应该为您提供一个新列,其中包含所有3列的最大值
df["max"] = df[["f1", "f2","f3"]].max(axis=1)
然后您可以在此列上运行最大值以获取最大值
df['max'].max()