通过从现有数据帧python中选择特定行来创建新数据帧

Shu*_*m R 7 python pandas

我的熊猫数据框中有一张桌子.DF

id count price
1    2     100
2    7      25
3    3     720
4    7     221
5    8     212
6    2     200
Run Code Online (Sandbox Code Playgroud)

我想从中创建一个新的数据帧(df2),选择count为2且price为100的行,count为7,price为221

我的输出应该是df2 =

id count price
1    2     100
4    7     221
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 df[df['count'] == '2' & df['price'] == '100']

但得到错误

TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 8

你需要添加()因为&优先级高于==:

df3 = df[(df['count'] == '2') & (df['price'] == '100')]
print (df3)
  id count price
0  1     2   100
Run Code Online (Sandbox Code Playgroud)

如果需要检查多个值,请使用isin:

df4 = df[(df['count'].isin(['2','7'])) & (df['price'].isin(['100', '221']))]
print (df4)
  id count price
0  1     2   100
3  4     7   221
Run Code Online (Sandbox Code Playgroud)

但如果检查数字,请使用:

df3 = df[(df['count'] == 2) & (df['price'] == 100)]
print (df3)

df4 = df[(df['count'].isin([2,7])) & (df['price'].isin([100, 221]))]
print (df4)
Run Code Online (Sandbox Code Playgroud)