首页 > 解决方案 > Pandas:选择 DataFrame 匹配和不匹配条件

问题描述

我有两个 DF,如下所示:

ID | A | B
1    0   1
2    1   2
3    2   2

Type | Name
1    |  ...
2    |  ...
1    |  ...

我想要第一个中的两个 DataFrame。第一个只有第二个 DF 中的Type == 1行,另一个包含第二个 DF 中的行Type != 1。这是我的样本期望结果:

First DF:
ID | A | B
1    0   1
3    2   2

Second DF:
ID | A | B
2    1   2

让我们称第一个df和第二个df_other。我试过了,但它给了我错误

idx = df_other["Type"] == 1
df1 = df[~df.index.isin(idx)]
df2 = df[df.index.isin(idx)]

我也试过loc[idx]and .iloc[idx, :],但他们也给出了错误的结果。任何帮助表示赞赏。

标签: pythonpandasdataframe

解决方案


让我们调用您的数据框df1df2. 我假设两者的长度相同。

import numpy as np
import pandas as pd

mask1 = np.select([df2['Type']==1, [True], default=False) #this creates a pandas series with True values were df2['Type'] is 1 and False everywhere else.

#### Your first dataframe would be
df1[mask1]
#### Your second dataframe is
df1[~mask1]

# if you want to save them as dataframes best use .copy() i.e.:
df_type1 = df1[mask1].copy()
df_typeNot1 = df1[~mask1].copy()


推荐阅读