【问题标题】:Using scalar values in series as variables in user defined function使用系列标量值作为用户定义函数中的变量
【发布时间】:2016-11-05 16:58:16
【问题描述】:

我想为数据框中的每一行定义一个按元素应用的函数,将每个元素与单独系列中的标量值进行比较。我从下面的函数开始。

def greater_than(array, value):
           g = array[array >= value].count(axis=1)
           return g

但它是沿轴 0 应用蒙版,我需要它沿轴 1 应用蒙版。我该怎么办?

例如

In [3]: df = pd.DataFrame(np.arange(16).reshape(4,4))

In [4]: df
Out[4]:
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

In [26]: s
Out[26]: array([   1, 1000, 1000, 1000])

In [25]: greater_than(df,s)
Out[25]:
0    0
1    1
2    1
3    1
dtype: int64

In [27]: g = df[df >= s]

In [28]: g
Out[28]:
      0   1   2   3
0   NaN NaN NaN NaN
1   4.0 NaN NaN NaN
2   8.0 NaN NaN NaN
3  12.0 NaN NaN NaN

结果应该是这样的:

In [29]: greater_than(df,s)
Out[29]:
0    3
1    0
2    0
3    0
dtype: int64

因为 1,2, & 3 都 >= 1 并且剩余的值都不大于或等于 1000。

【问题讨论】:

  • 那么,样本的预期输出是什么?
  • @Divakar,谢谢,我已经添加了预期的输出。

标签: pandas axis user-defined-functions mask


【解决方案1】:

您最好的选择可能是进行一些转置(如果担心,则不制作副本)

In [164]: df = pd.DataFrame(np.arange(16).reshape(4,4))

In [165]: s = np.array([   1, 1000, 1000, 1000])

In [171]: df.T[(df.T>=s)].T
Out[171]: 
    0    1    2    3
0 NaN  1.0  2.0  3.0
1 NaN  NaN  NaN  NaN
2 NaN  NaN  NaN  NaN
3 NaN  NaN  NaN  NaN

In [172]: df.T[(df.T>=s)].T.count(axis=1)
Out[172]: 
0    3
1    0
2    0
3    0
dtype: int64

如果计数就是你所追求的,你也可以直接对掩码求和。

In [173]: (df.T>=s).sum(axis=0)
Out[173]: 
0    3
1    0
2    0
3    0
dtype: int64

【讨论】:

  • 谢谢。我已经考虑过这一点,但希望有一些使用定义函数的固有方法,比如改变计数轴或其他东西。我想学习如何控制这些参数,以便在未来拥有更大的灵活性。
  • 您可以使用apply 获取要在右轴上应用的蒙版。 例如 df[df.apply(lambda r: r >=s)].count(axis=1),但转置和求和对我来说大约是 2 倍。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2016-03-15
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多