python - 按另一个数据框中的值分组

标签 python pandas

我有两个数据帧 A 和 B。两者具有相同的结构(行数、列数、列名和索引)。 A 填充了数据,B 包含与 A 中的数据相对应的标志(True 或 False)。我想创建另一个数据帧 C,每当 B 中的相应标志为 True 时,它​​就具有 A 的值。我该怎么做呢?我相信我必须使用某种分组方式,但我是 python/pandas 的新手。

最佳答案

类似这样的吗?

>>A = pd.DataFrame({'col1':[2,3,4,5],'col2':['a','b','c','d']})
>>A

col1    col2
0   2   a
1   3   b
2   4   c
3   5   d

>>B = pd.DataFrame({'col1':[True, True, False, False],'col2':[False, False,True,True]})
>>B

col1    col2
0   True    False
1   True    False
2   False   True
3   False   True

>>C = A[B]

col1    col2
0   2.0 NaN
1   3.0 NaN
2   NaN c
3   NaN d

关于python - 按另一个数据框中的值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44987158/

相关文章:

python / Pandas : how to read a csv in cp1252 with a first row to delete?

Python matplotlib.pyplot 饼图 : How to remove the label on the left side?

python - 在包含缺失值的 Pandas 数据框列上使用 apply 和 lambda 函数

python - 如果模式匹配,则将两个列表组合成字典

python - Matplotlib:imshow 中的 set_data 对绘图没有影响

python - 将数据类型 "object"转换为 "Float"

python - 熔化和删除重复数据帧的反转

python - try 和 except 都引发异常。

python - 无法让 entrez 使用 biopython 返回网格项

python - Pandas 根据列的值有效地分块读取大型面板 CSV