python 如何在pandas中动态创建新列,就像我们在pysparkwithColumn中所做的那样

qlvxas9a  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(102)
from statistics import mean
import pandas as pd
df = pd.DataFrame(columns=['A', 'B', 'C'])
df["A"] = [1, 2, 3, 4, 4, 5, 6]
df["B"] = ["Feb", "Feb", "Feb", "May", "May", "May", "May"]
df["C"] = [10, 20, 30, 40, 30, 50, 60]
df1 = df.groupby(["A","B"]).agg(mean_err=("C", mean)).reset_index()

df1["threshold"] = df1["A"] * df1["mean_err"]

如果不使用最后一行代码,我如何像在Pyspark.withColumn()中那样做呢?

这段代码不起作用。我想通过在运行中使用操作的输出来创建新列,类似于我们在Pyspark withColumn方法中所做的。
有人知道怎么做吗?

exdqitrt

exdqitrt1#

选项一:DataFrame.eval

(df.groupby(['A', 'B'], as_index=False)
   .agg(mean_err=('C', 'mean'))
   .eval('threshold = A * mean_err'))

选项二:DataFrame.assign

(df.groupby(['A', 'B'], as_index=False)
   .agg(mean_err=('C', 'mean'))
   .assign(threshold=lambda x: x['A'] * x['mean_err']))
A    B  mean_err  threshold
0  1  Feb      10.0       10.0
1  2  Feb      20.0       40.0
2  3  Feb      30.0       90.0
3  4  May      35.0      140.0
4  5  May      50.0      250.0
5  6  May      60.0      360.0

相关问题