我有一个数据框。我想将具有特定参数值的行中所有小于x的值设置为新值。
我尝试了一下,但是我的数据框没有任何反应。
df_data = {'A': [4, 4, 5, 5],
'B': [4, 4, 4, 5],
'C': [4, 5, 5, 5],
'Bool': [True, True, False, False]}
test_df = pd.DataFrame(df_data, columns=['A', 'B', 'C', 'Bool'])
test_df[test_df.iloc[:, :-1] < 5][test_df['Bool'] == True] = 99
print(test_df)
我希望test_df中的某些元素具有值99。
最佳答案
如果需要将DataFrame
和&
的布尔布尔值按位AND转换为numpy数组(N,1),然后使用DataFrame.mask
设置新值:
m = (test_df.iloc[:, :-1] < 5).values & test_df['Bool'].values[:, None]
print (m)
[[ True True True]
[ True True False]
[False False False]
[False False False]]
test_df.iloc[:, :-1] = test_df.iloc[:, :-1].mask(m, 99)
print(test_df)
A B C Bool
0 99 99 99 True
1 99 99 5 True
2 5 4 5 False
3 5 5 5 False