Python Pandas Concat "WHERE" a条件满足

Python Pandas Concat "WHERE" a Condition is met

如何 "concat" 来自许多 Python Pandas 数据帧的特定列,其中每个数据帧中的另一列满足特定条件(通俗地称为条件 "X" 此处)。

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

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

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

考虑 list dfs of pd.DataFrames

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

另一种方法
使用 query

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