我有一个如下所示的数据框:
item storage
record paper
record laptop
record desktop
file laptop
file paper
file paper
record desktop
file desktop
如果我想要一个包含2个条件的新数据框,例如'记录'在项目列和'笔记本电脑'或存储列中的桌面是一种更简单的方法来选择此数据集而不是:
df1=df[(df['item'] == 'record') & (df['storage'] == 'laptop')]
df2=df[(df['item'] == 'record') & (df['storage'] == 'desktop')]
df3= pd.concat([df1, df2], axis=1)
是否有一种较短的方法可以在一行中执行此操作,如:
df3=df[(df['item'] == 'record') & (df['storage'] == 'laptop' or 'desktop')] #This does not work
答案 0 :(得分:3)
您可以将其中一个条件更改为.isin
:
>>> df['storage'].isin(['laptop', 'desktop'])
这样:
>>> df[(df['item'] == 'record') & (df['storage'].isin(['laptop', 'desktop']))]
item storage
1 record laptop
2 record desktop
6 record desktop