如何在DataFrame中创建和使用新功能?

问题描述 投票:0回答:1

如何创建新函数并在DataFrame中使用此新函数,以便在聚合期间添加新列?从我的DataFrame中,我选取了“风向”和“温度”,对于这些列,我想对其进行汇总,并创建平均值为“风向”的表格,以及所有城市的均值和平均值“ aa”之间的差,而对于“温度”。但是,在使用函数“ aa”的列中,我有0。问题出在哪里,您能给我写合适的代码行吗?

def aa(x):
    return x - np.mean(x)

file.groupby(["City"]).agg({"Wind direction":[np.mean, aa], "Temperature":["mean", aa]})
python pandas function dataframe aggregates
1个回答
0
投票

您正在错误的分组级别应用aa。这里有个简单的例子:

np.random.seed(1)
size = 10
file = pd.DataFrame({
    'City': np.random.choice(list(string.ascii_uppercase), size),
    'Wind direction': np.random.randint(0, 360, size),
    'Temperature': np.random.randint(1, 100, size)
}).sort_values('City').reset_index(drop=True)

df

  City  Wind direction  Temperature
0    A             252           87
1    F             129           30
2    F             254           95
3    I             281           69
4    J             178           88
5    L              71           15
6    L             276           88
7    M             237           51
8    P             357           97
9    Q             156           14

您的原始代码...

def aa(x):
    return x - np.mean(x)

file.groupby(["City"]).agg({"Wind direction":[np.mean, aa], "Temperature":["mean", aa]})

..结果:

     Wind direction                  Temperature               
               mean               aa        mean             aa
City                                                           
A             252.0                0        87.0              0
F             191.5    [-62.5, 62.5]        62.5  [-32.5, 32.5]
I             281.0                0        69.0              0
J             178.0                0        88.0              0
L             173.5  [-102.5, 102.5]        51.5  [-36.5, 36.5]
M             237.0                0        51.0              0
P             357.0                0        97.0              0
Q             156.0                0        14.0              0

请注意,只有两次出现的城市在结果表中具有值?当您只有1个城市的数据点时,请按x == np.mean(x),以便它们的差为0。


解决方案

将聚合函数定义为:

def aa(col):
    # Difference between the mean value of each city and the global (entire column) mean
    return col.mean() - file[col.name].mean()

file.groupby(["City"]).agg({"Wind direction":[np.mean, aa], "Temperature":["mean", aa]}) 

结果:

     Wind direction        Temperature      
               mean     aa        mean    aa
City                                        
A             252.0   32.9        87.0  23.6
F             191.5  -27.6        62.5  -0.9
I             281.0   61.9        69.0   5.6
J             178.0  -41.1        88.0  24.6
L             173.5  -45.6        51.5 -11.9
M             237.0   17.9        51.0 -12.4
P             357.0  137.9        97.0  33.6
Q             156.0  -63.1        14.0 -49.4
© www.soinside.com 2019 - 2024. All rights reserved.