R根据逻辑条件取子集的熊猫等价物是多少?



我想计算从r到pandas的等效物:

df$received[df$gender == 'F']

在熊猫中,如果我使用:

df['received'][df['gender'] == 'F']

它不起作用。

或者如果我尝试:

df['received'] & df['gender'] == 'F'

它给了我: unsupported operand type(s) for &: 'float' and 'bool'

看来您需要loc使用boolean indexing

df.loc[df['gender'] == 'F', 'received']

样本:

df = pd.DataFrame({'gender':['F','M','F'], 'received':[10,20,50]})
print (df)
  gender  received
0      F        10
1      M        20
2      F        50
print (df.loc[df['gender'] == 'F', 'received'])
0    10
2    50
Name: received, dtype: int64

相关内容

  • 没有找到相关文章

最新更新