Skip to main content
 首页 » 编程设计

python之通过将函数应用于另一个数据框的列来创建新数据框

2025年05月04日15linjiqin

我尝试学习更多关于 python 中的 apply 方法,并问自己如何使用 apply 编写以下代码:

我有一个如下所示的数据框 df:

  A B C D E points 
0 0 0 0 1 43 94 
1 0 0 1 1 55 62 
2 1 1 0 1 21 84 
3 1 0 1 0 13 20 

此外,我还有一个像下面这样的函数,它完成了它的工作:

def f1(df): 
  df_means = pd.DataFrame(columns = ['Mean_Points']) 
  for columnname in df.columns: 
    if len(df[df[columnname] == 1]) > 1: 
      df_means.loc[columnname] = [df[df[columnname] == 1]['points'].mean()] 
  return df_means 

所以f1的输出是

  'Mean_Points' 
A      52 
C      41 
D      80 

这完全没问题。 但我想知道是否有可能(我确信有)使用 apply 方法获得相同的结果。 我试过:

df_means = pd.DataFrame(columns = ['Mean_Points']) 
cols = [col for col in df.columns if len(df[df[col] == 1]) > 1] 
df_means.loc[cols] = df[cols].apply(lambda x: df[df[x] == 1]['points'].mean(), axis = 1) 

或类似的:

df_means = pd.DataFrame(columns = ['Mean_Points']) 
df.columns.apply(lambda x: df_means.loc[x] = [df[df[x] == 1]['points'].mean()] if len(df[df[x] == 1]) > 1 else None) 

和 2,3 其他东西,但没有任何效果...... 我希望有人能在这里帮助我?!

请您参考如下方法:

pd.DataFrame.dot

#                      filters s to be just those 
#                      things greater than 1 
#                      v 
s = df.eq(1).sum().loc[lambda x: x > 1] 
df.loc[:, s.index].T.dot(df.points).div(s) 
 
A    52.0 
C    41.0 
D    80.0 
dtype: float64 

单线法

这消除了干扰,但可能会进行不必要的计算。

df.T.dot(df.points).div(df.sum())[df.eq(1).sum().gt(1)] 
 
A    52.0 
C    41.0 
D    80.0 
dtype: float64