Skip to main content
 首页 » 编程设计

python之如何创建自己的方法并在 DataFrame 中使用它

2024年11月01日7lonelyxmas

我有包含以下列的 DataFrame:城市、风向、温度。当然每个城市只出现 1 次!!!并且只有 1 个风向和温度数据点。例如: 0 纽约 252.0 22.0

如何创建我自己的 methon 并在 DataFrame 中使用它?例如,我想创建自己的方法“aa”,它返回一些解决方案(城市温度减去整个“温度”列的平均温度),并在聚合我的 DataFrame 期间使用这个创建的方法。 目前我创建了方法“aa”,如下所示,我在聚合中使用它,但是,“aa”方法到处都显示“0”。你能给我写一个合适的代码吗?我弄错了 id def aa(x) 吗?

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

示例数据:(取自 OP 提供的评论)

file = pd.DataFrame({"City":["New York", "Berlin", "London"], "Wind direction":[225.0, 252.0, 310.0], "Temperature":[21.0, 18.5, 22.0]}) 

请您参考如下方法:

你得到零是因为 aa 接收的输入是组,而不是整个系列,并且单元素组的平均值是单个元素。

现在,当您知道每个组只有一个元素时,使用 groupby 有点奇怪,但您可以通过使用类似的东西来强制它

def aa(x): 
    return x - file[x.name].mean() 

以你给出的例子:

In [23]: file.groupby(["City"]).agg({"Wind direction":[np.mean, aa], "Temperature":["mean", aa]}) 
Out[23]: 
         Wind direction            Temperature 
                   mean         aa        mean   aa 
City 
Berlin            252.0 -10.333333        18.5 -2.0 
London            310.0  47.666667        22.0  1.5 
New York          225.0 -37.333333        21.0  0.5 

更直接的方法是直接对数据框进行操作,例如

In [26]: file['Wind direction aa'] = file['Wind direction'] - file['Wind direction'].mean() 
 
In [27]: file['Temperature aa'] = file['Temperature'] - file['Temperature'].mean() 
 
In [28]: file 
Out[28]: 
       City  Wind direction  Temperature  Wind direction aa  Temperature aa 
0  New York           225.0         21.0         -37.333333             0.5 
1    Berlin           252.0         18.5         -10.333333            -2.0 
2    London           310.0         22.0          47.666667             1.5