woodhead92 - 11 months ago 60

Python Question

I have the following dataframe in python

`+-------+--------+`

| Value | Number |

+-------+--------+

| true | 123 |

| false | 234 |

| true | 345 |

| true | 456 |

| false | 567 |

| false | 678 |

| false | 789 |

+-------+--------+

How do I conduct an operation which returns a list of all the 'Number' which has Value == TRUE

The output list expected from the above table is

`['123', '345', '456']`

Thanks in advance!

Answer Source

`df.loc[df['Value'],'Number']`

should work assuming the dtype for 'Value' are real booleans:

```
In [68]:
df.loc[df['Value'],'Number']
Out[68]:
0 123
2 345
3 456
Name: Number, dtype: int64
```

The above uses boolean indexing, here the boolean values are a mask against the df.

If you want a `list`

:

```
In [69]:
df.loc[df['Value'],'Number'].tolist()
Out[69]:
[123, 345, 456]
```