我想将一个数据框中的许多列与一列进行比较。有没有这样做的非循环方法?
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9], 'd':[5,7,2]})
# works but requires one line per column
df['a'] = df['a'] < df['d']
df['b'] = df['b'] < df['d']
df['c'] = df['c'] < df['d']
# df[['a','b','c']] = df[['a','b','c']] < df[['d']]
答案 0 :(得分:3)
将DataFrame.lt
与axis=0
方法一起使用,从选择[]
中删除一个d
以供Series
选择:
df[['a','b','c']] = df[['a','b','c']].lt(df['d'], axis=0)
print (df)
a b c d
0 True True False 5
1 True True False 7
2 False False False 2
或者您可以按从列d
创建的numpy数组进行比较:
df[['a','b','c']] = df[['a','b','c']] < df['d'].to_numpy()
print (df)
a b c d
0 True True False 5
1 True True False 7
2 True True False 2