Python DataFrame - 根据另一个数据帧中的值选择数据帧行

标签 python pandas dataframe

我正在努力解决与数据框相关的问题。有两个数据帧,df和dff,如下

data = np.array([['', 'col1', 'col2'],
            ['row1', 1, 2],
            ['row2', 3, 4]])
df = pd.DataFrame(data=data[1:,1:].astype(int), index=data[1:,0],columns=data[0,1:])


filters=np.array([['', 'col1', 'col2'],
                 ['row1', 1, 1],
                 ['row2', 1, 2],
                 ['row3', 3, 2]])
dff = pd.DataFrame(data=filters[1:,1:].astype(int), index=filters[1:,0],columns=filters[0,1:])

我希望从 df 中选择行,使其 col2 值属于可以在 dff 中找到且具有匹配 col1 值的值列表。 例如,对于 col1 值等于 1,该列表应为 [1, 2],对于 col1 值等于 2,该列表应为 [2]。

我解决这个问题的最佳尝试是

df1 = df[df['col2'].isin(dff[dff['col1']==df['col1']]['col2'])]

但这会导致

ValueError: Can only compare identically-labeled Series objects

如有任何帮助,我们将不胜感激。非常感谢。

最佳答案

据我了解,您可以简单地 aggregate

ndf = dff.groupby('col1').agg(lambda x: list(x)).reset_index()

    col1   col2
0   1      [1, 2]
1   3      [2]

并过滤 col1 中不在 df

中的值
ndf[ndf.col1.isin(df.col1)]

关于Python DataFrame - 根据另一个数据帧中的值选择数据帧行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898313/

相关文章:

python - 发送不改变用户当前页面的 HTTP 响应

python - 比较两列并用数字替换 NaN

pandas - Pandas DataFrame 的空副本

按同名列分组的行值总和

使用 urllib2 的 Python 表单 POST(还有关于保存/使用 cookie 的问题)

python - 在 linux 基础机器上使用 python dragonfly 的问题

python - 仅通过标准 python 套接字获取 Tor7.0 的新 IP

python - R中的规则时间间隔

python - 时间序列重采样

python - Pandas,使用 dt.date 或 dt.strftime 从日期时间列中删除时间戳,将列转换为 dtype : object