pandas 通过从现有 Dataframe python中选择特定行创建新 Dataframe

ubby3x7f  于 2022-12-02  发布在  Python
关注(0)|答案(2)|浏览(120)

我有一个表在我的Pandasdataframe.df

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

我想以此为基础创建一个新的 Dataframe (df2),选择count为2、price为100以及count为7、price为221的行
我的输出应该是df2 =

id count price
1    2     100
4    7     221

我正在尝试使用df[df['count'] == '2' & df['price'] == '100']
但发生错误

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

shyt4zoc1#

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

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

如果需要检查多个值,请使用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

但如果检查数值,则用途:

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

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

kg7wmglp2#

如果要按索引id执行操作,可以执行以下操作:
新的文件格式=(文件格式.iloc1).append(文件格式.iloc6

相关问题