python - 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, :]
,但他们也给出了错误的结果。任何帮助表示赞赏。
解决方案
让我们调用您的数据框df1
和df2
. 我假设两者的长度相同。
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()
推荐阅读
- javascript - Electron JS - 无法解构'require(...).remote'的属性'BrowserWindow',因为它未定义
- javascript - 导航回具有相同状态的搜索页面 (JavaScript)
- google-play - 如何从 Google Play 音乐转移到 Plex 音乐
- snowflake-cloud-data-platform - 从命名的外部阶段与外部位置加载文件
- python - 如何更改 RS4 类属性的默认值 - rpy2
- python - 如何通过列表值命名在 for 循环中开发的每个数据框
- python - 用 NaN 替换组的最后一个值
- c++ - C++创建一个函数的朋友?
- jquery - jQuery查找元素
- css - 为不透明度应用的 CSS 规则与计算的样式不同