从现有数据帧 python 中选择特定行创建一个新的数据帧 [英] create a new dataframe from selecting specific rows from existing dataframe python

查看:52
本文介绍了从现有数据帧 python 中选择特定行创建一个新的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的熊猫数据框中有一张表格.df

i have a table in my pandas dataframe. df

id count price
1    2     100
2    7      25
3    3     720
4    7     221
5    8     212
6    2     200

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

i want to create a new dataframe(df2) from this, selecting rows where count is 2 and price is 100,and count is 7 and price is 221

我的输出应该是 df2 =

my output should be df2 =

id count price
1    2     100
4    7     221

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

但出现错误

TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]

推荐答案

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

You nedd add () because & has higher precedence than ==:

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

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

If need check multiple values use 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

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

But if check numeric, use:

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

df4 = df[(df['count'].isin([2,7])) & (df['price'].isin([100, 221]))]
print (df4)

这篇关于从现有数据帧 python 中选择特定行创建一个新的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆