【问题标题】:How can create my own method and use it in DataFrame?如何创建自己的方法并在 DataFrame 中使用它?
【发布时间】:2020-02-17 08:23:55
【问题描述】:

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

如何创建自己的方法并在 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 提供的 cmets)

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

【问题讨论】:

  • 不,我想创建自己的方法“aa”并实现它 .agg() 函数,我需要这样做,我知道这是可能的,但是我不知道我的代码中的错误在哪里。
  • 添加一些示例数据
  • 我在函数中使用了 x - np.mean(x) 因为我想从给定城市的温度中减去所有城市的平均温度,然后使用 .agg() 创建表像这样: City-----Temperature in City-----Temperature in City - 平均温度和风向相同
  • 为此,您需要更改此np.mean(x) 以通过np.mean(file[x.name]) 获取列的平均值。

标签: python pandas dataframe methods aggregation


【解决方案1】:

你得到零是因为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

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2021-12-18
    • 2015-08-24
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多