首页 > 解决方案 > 将基于统计信息的新列添加到 DataFrame

问题描述

这是我的第一个问题。我想建立一个统计模型。我有一个数据,我想在这个数据框中添加一列。我希望这个专栏展示一些统计数据。例如我的数据框是这样的

数据框

例如,我想添加一个新列。我希望这个栏目显示“车红女孩”的 D 值大于所有车的 D 的平均值,我该怎么做?我应该使用哪种方式来做这个统计模型。我有大量数据,无法手动计算所有汽车或自行车的平均值。我需要一个带有 if-else 语句的函数,并添加一列来描述该行的 D 大于或小于平均值。

我的代码是这样的,但是我得到了 Key Error 0。

for b in list(df.A.unique()):
    for i in range(len(df.loc[df.A == b])):
        if df.loc[df.A == b, "D"][i] >= df.loc[df.A == b,"D"].mean():
            df.loc[df.A== b]["E"][i] = "Bigger"

标签: pythonpandasfunctionif-statementstatistics

解决方案


这可以使用pandas库来实现。假设,您DataFrame存储在变量中df

第 1 步 - 计算列的平均值

第 2 步 - 获取列值大于列平均值的索引

第 3 步 - 将这些索引中的值设置为 True

mean_D=df.loc[:,"D"].mean()
df.loc[:,"E"]=False #Set Initially to 'False' implying D's mean is less than column mean
indices=df[df.loc[:,"D"]>mean_D].index
df.loc[indices,"E"]=True

编辑 1

  1. 将个体平均值存储在字典中

  2. 计算值大于平均值的相应索引(单独)

  3. 将索引设置为True

from collections import defaultdict
df=pd.DataFrame({"A":['car','car','car','bike','bike','bike'],"B":['red','red','blue','black','white','red'],"C":['girl','boy','boy','boy','girl','girl'],"D":[8,7,6,9,10,7]})
dict_car_bike=defaultdict(list)
for i, temp in df.groupby("A"):
    dict_car_bike[temp.loc[:,"A"].unique()[0]]=temp.loc[:,"D"].mean()

dict_car_bike=dict(dict_car_bike)

df.loc[:,"E"]=False #Set Initially to 'False' implying D's mean is less than column mean
indices_0=df[(df.A.astype(str)==list(dict_car_bike.keys())[0]) & (df.D>dict_car_bike[list(dict_car_bike.keys())[0]])].index
indices_1=df[(df.A==list(dict_car_bike.keys())[1]) & (df.D>dict_car_bike[list(dict_car_bike.keys())[1]])].index
df.loc[indices_0,"E"]=True
df.loc[indices_1,"E"]=True

输出

Output DataFrame

     A      B     C    D      E
0   car    red  girl   8   True
1   car    red   boy   7  False
2   car   blue   boy   6  False
3  bike  black   boy   9   True
4  bike  white  girl  10   True
5  bike    red  girl   7  False

Output Dictionary with Corresponding Mean

{'bike': 8.666666666666666, 'car': 7.0}

推荐阅读