Skip to main content
 首页 » 编程设计

Python Pandas Concat "WHERE"满足条件

2025年04月02日7sharpest

我如何“连接”许多 Python Pandas 数据框中的特定列,其中每个数据框中的另一列满足特定条件(此处通俗地称为条件“X”)。

在 SQL 中,使用带有 WHERE df2.Col2 = "X"和 df3.Col2 = "X"和 df4.col2 = "X"等的 JOIN 子句会很简单(可以动态运行)。

在我的例子中,我想创建一个大数据帧,其中包含许多数据帧中每个数据帧的所有“Col1”,但只包括 Col1 行值,其中相应的 Col2 行值大于“0.8”。当不满足此条件时,Col1 值应为“NaN”。

任何想法都会很有帮助!提前致谢!

请您参考如下方法:

考虑 pd.DataFrames 的 list dfs

import pandas as pd 
import numpy as np 
 
 
np.random.seed([3,1415]) 
dfs = [pd.DataFrame(np.random.rand(10, 2), 
                    columns=['Col1', 'Col2']) for _ in range(5)] 

我将使用pd.concat 加入

原始连接
堆栈值而不考虑它来自哪里

pd.concat([d.Col1.loc[d.Col2.gt(.8)] for d in dfs], ignore_index=True) 
 
0     0.850445 
1     0.934829 
2     0.879891 
3     0.085823 
4     0.739635 
5     0.700566 
6     0.542329 
7     0.882029 
8     0.496250 
9     0.585309 
10    0.883372 
Name: Col1, dtype: float64 

加入源信息
使用 keys 参数

pd.concat([d.Col1.loc[d.Col2.gt(.8)] for d in dfs], keys=range(len(dfs))) 
 
0  3    0.850445 
   5    0.934829 
   6    0.879891 
1  1    0.085823 
   2    0.739635 
   7    0.700566 
2  4    0.542329 
3  3    0.882029 
   4    0.496250 
   8    0.585309 
4  0    0.883372 
Name: Col1, dtype: float64 

另一种方法
使用查询

pd.concat([d.query('Col2 > .8').Col1 for d in dfs], keys=range(len(dfs))) 
 
0  3    0.850445 
   5    0.934829 
   6    0.879891 
1  1    0.085823 
   2    0.739635 
   7    0.700566 
2  4    0.542329 
3  3    0.882029 
   4    0.496250 
   8    0.585309 
4  0    0.883372 
Name: Col1, dtype: float64