首页 > 解决方案 > 如何在 DataFrame 中创建和使用新函数?

问题描述

如何在我的 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]})

标签: pythonpandasfunctiondataframeaggregates

解决方案


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 local (city) mean 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

推荐阅读