在具有多个元素条件的数据框中设置值
Set values in dataframe with multiple element-wise conditions
我有一个数据框。我想将具有特定参数值的行中所有小于 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
和 &
进行按位与运算,则必须将其转换为 numpy 数组 (N, 1),然后使用 DataFrame.mask
:[=15 设置新值=]
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
这个有效:
m = (test_df.iloc[:, :-1] < 5) & (pd.DataFrame(pd.np.tile((test_df['Bool'].values[:, None] == True), (1, 3)))).values
test_df.iloc[:, :-1] = test_df.iloc[:, :-1].mask(m, 99)
我有一个数据框。我想将具有特定参数值的行中所有小于 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
和 &
进行按位与运算,则必须将其转换为 numpy 数组 (N, 1),然后使用 DataFrame.mask
:[=15 设置新值=]
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
这个有效:
m = (test_df.iloc[:, :-1] < 5) & (pd.DataFrame(pd.np.tile((test_df['Bool'].values[:, None] == True), (1, 3)))).values
test_df.iloc[:, :-1] = test_df.iloc[:, :-1].mask(m, 99)