如何分配数据帧[boolean Mask] =系列 - 按行划分?即其中Mask = true从系列的同一行获取值

时间:2017-10-16 08:54:48

标签: python pandas

我有一个数据帧,布尔掩码(例如boolMask = df< = 1)和一系列的 与df相同的垂直尺寸,我想写类似

的东西
import { injectGlobal } from 'styled-components';

injectGlobal`
  html {
    height: 100%;
    width: 100%;
  }
`

即。对boolMask = TRUE的数据框元素进行赋值, 我想按行进行分配,即从中分配一个元素 系列行到DataFrame中的同一行

df[ boolMask ] = ser

书写

df = pd.DataFrame([[1, 2 ], [3, 4], [5 , 6]] ) 
ser = pd.Series([1, 2, 3 ])
boolMask = df <= 1

导致错误: ValueError:必须指定axis = 0或1

1 个答案:

答案 0 :(得分:1)

我认为你需要mask

df = pd.DataFrame([[1, 2 ], [3, 4], [5 , 0]] ) 
print (df)
   0  1
0  1  2
1  3  4
2  5  0

ser = pd.Series([10, 20, 30 ])
boolMask = df <= 1

print (boolMask)
       0      1
0   True  False
1  False  False
2  False   True

#replace first and second value of ser - row processing
df1 = df.mask(boolMask, ser, axis=1)
print (df1)
    0   1
0  10   2
1   3   4
2   5  20

#replace first and third value of ser - column processing
df2 = df.mask(boolMask, ser, axis=0)
print (df2)
    0   1
0  10   2
1   3   4
2   5  30