谢谢你的帮助。我对熊猫还比较陌生,在搜索结果中没有观察到这种特殊的查询
我有一个数据框:
+-----+---------+----------+
| id | value | match_id |
+-----+---------+----------+
| A10 | grass | 1 |
| B45 | cow | 3 |
| B98 | bird | 6 |
| B17 | grass | 1 |
| A20 | tree | 2 |
| A87 | farmer | 5 |
| B11 | grass | 1 |
| A33 | chicken | 4 |
| B56 | tree | 2 |
| A23 | farmer | 5 |
| B65 | cow | 3 |
+-----+---------+----------+
我需要过滤这个数据帧中包含匹配的match_id
值的行,条件是id
列必须同时包含两个字符串A
和{
这是预期输出:
+-----+-------+----------+
| id | value | match_id |
+-----+-------+----------+
| A10 | grass | 1 |
| B17 | grass | 1 |
| A20 | tree | 2 |
| B11 | grass | 1 |
| B56 | tree | 2 |
+-----+-------+----------+
比如说,我如何在一行代码中做到这一点?可复制程序如下:
import pandas as pd
data_example = {'id': ['A10', 'B45', 'B98', 'B17', 'A20', 'A87', 'B11', 'A33', 'B56', 'A23', 'B65'],
'value': ['grass', 'cow', 'bird', 'grass', 'tree', 'farmer', 'grass', 'chicken', 'tree', 'farmer', 'cow'],
'match_id': [1, 3, 6, 1, 2, 5, 1, 4, 2, 5, 3]}
df_example = pd.DataFrame(data=data_example)
data_expected = {'id': ['A10', 'B17', 'A20', 'B11', 'B56'],
'value': ['grass', 'grass', 'tree', 'grass', 'tree'],
'match_id': [1, 1, 2, 1, 2]}
df_expected = pd.DataFrame(data=data_expected)
谢谢大家!
单行似乎很难,但您可以
str.extract
从id中选择想要的两个字符串,然后groupby
匹配any
并使用any
查看每个匹配^{id是否至少有一行具有所需的字符串之一,然后使用轴1的all
将提供True
来匹配这两个字符串。然后,您可以使用刚刚创建的序列在map
match_id列之后仅选择True match_id对@Ben.T解决方案的不同理解:
相关问题 更多 >
编程相关推荐