首页 > 解决方案 > 根据两个标准从数据框中提取数据

问题描述

给出以下示例。

d = {'col1': [1, 2, 3], 'col2': [6, 7]}

df = pd.DataFrame(data=d)

df
   col1  col2
0     1     6
1     2     7

newdf[df['col1' ==2]

newdf

   col1  col2
0     2     7

适用于单色

newdf[df['col1' ==2 & 'col2' == 7]

我赢得了错误奖。

标签: pythondataframe

解决方案


  • 以下都不正确

    • newdf[df['col1' ==2]
    • newdf[df['col1' ==2 & 'col2' == 7]
    • newdf[df['col1' == 2 && 'col2' == 7]
  • 括号必须围绕每个条件

  • Pandas:布尔索引
import pandas as pd

d = {'col1': [1, 2, 3, 2], 'col2': [6, 7, 8, 9]}
df = pd.DataFrame(data=d)

   col1  col2
0     1     6
1     2     7
2     3     8
3     2     9

# specify multiple conditions
newdf = df[(df.col1 == 2) & (df.col2 == 7)]
print(newdf)

   col1  col2
1     2     7

推荐阅读