Skip to main content
 首页 » 编程设计

python之在一个 df 上创建具有条件的 lambda 函数以在另一个 df 的 df.apply 中使用

2024年10月17日29TianFang

考虑 df

Index   A         B      C 
0      20161001   0      24.5 
1      20161001   3      26.5 
2      20161001   6      21.5 
3      20161001   9      29.5 
4      20161001   12     20.5 
5      20161002   0      30.5 
6      20161002   3      22.5 
7      20161002   6      25.5 
... 

同时考虑 df2

Index Threshold 
0     25 
1     27 
2     29 
3     30 
4     25 
5     30 
.. 

我想添加一列"Number of Rows"至 df2其中包含 df 中的行数其中 (C > Threshold) & (A >= 20161001) & (A <= 20161002)成立。这基本上是在暗示 df 中不止一列有条件。

Index Threshold  Number of Rows  
0     25         4 
1     27         2 
2     29         2 
3     30         1 
4     25         4 
5     30         1 
.. 

对于 Threshold=25在 df2 , df 中有 4 行其中 "C"值超过 25。

我试过类似的方法:

def foo(threshold,start,end): 
    return len(df[(df['C'] > threshold) & (df['A'] > start) & (df['A'] < end)]) 
 
df2['Number of rows'] = df.apply(lambda df2: foo(df2['Threshold'],start = 20161001, end = 20161002),axis=1) 

但这正在填充 Number of Rows列为 0。这是为什么?

请您参考如下方法:

您可以使用 bool 索引和 sum() 聚合函数

# Create the first dataframe (df) 
df = pd.DataFrame([[20161001,0 ,24.5], 
                   [20161001,3 ,26.5], 
                   [20161001,6 ,21.5], 
                   [20161001,9 ,29.5], 
                   [20161001,12,20.5], 
                   [20161002,0 ,30.5], 
                   [20161002,3 ,22.5], 
                   [20161002,6 ,25.5]],columns=['A','B','C']) 
 
# Create the second dataframe (df2) 
 
df2 = pd.DataFrame(data=[25,27,29,30,25,30],columns=['Threshold']) 
 
start = 20161001 
end = 20161002 
 
df2['Number of Rows'] = df2['Threshold'].apply(lambda x : ((df.C > x) & (df.A >= start) & (df.A <= end)).sum()) 
 
print(df2['Number of Rows']) 
 
Out[]:  
       0    4 
       1    2 
       2    2 
       3    1 
       4    4 
       5    1 
       Name: Number of Rows, dtype: int64