【问题标题】:Applying a function to pandas DataFrame across columns to create temporary column for sorting跨列将函数应用于pandas DataFrame以创建用于排序的临时列
【发布时间】:2020-01-02 01:03:20
【问题描述】:

基于Sort pandas DataFrame with function over column values

我想使用.assign() 方法将log() 之类的函数应用于数据框,以创建临时列并将其用作排序条件,但是,我不能像这样传递轴参数它适用于.apply() 方法。

这是一个示例代码:

from numpy.random import randint

set.seed(0)
df = pd.DataFrame({'value':[randint(1,10) for i in range(0,10)], 'reading': [randint(1,10) for i in range(0,10)]})
   value  reading
0      8        6
1      5        9
2      3        7
3      8        2
4      6        1
5      4        9
6      6        2
7      3        5
8      2        2
9      8        8

我不能像这样使用 .assign() 方法:

df.assign(log = log(df.value/df.reading))

    raise TypeError("cannot convert the series to " "{0}".format(str(converter)))
TypeError: cannot convert the series to <class 'float'>

df.assign(log = lambda x: log(x.value/x.reading))

    raise TypeError("cannot convert the series to " "{0}".format(str(converter)))
TypeError: cannot convert the series to <class 'float'>

但它适用于 .apply() 方法:

df.apply(lambda x: log(x.value/x.reading), axis=1)

0    0.287682
1   -0.587787
2   -0.847298
3    1.386294
4    1.791759
5   -0.810930
6    1.098612
7   -0.510826
8    0.000000
9    0.000000
dtype: float64

任何解决方法可以使用 assign 或其他方法将其用作排序中的临时列?

【问题讨论】:

  • 你从哪里得到lognp.log 对我有用。
  • 来自数学导入日志
  • math.log 将期望一个标量实体——即单个 float。使用numpy.log,因为它适用于任何支持数组接口(包括熊猫系列)的东西
  • 我也有一些自定义函数有同样的问题,都是关于传递axis=1参数的。
  • 感谢@mgilson,解决了部分问题!

标签: python python-3.x pandas dataframe


【解决方案1】:

当您必须逐行执行操作时,您应该尽可能多地使用矢量化函数并保留apply(..., axis=1) 作为最后的手段。

你的问题可以用np.log解决,矢量化了:

df.assign(log=lambda x: np.log(x['value'] / x['reading']))

如果您有自定义函数,最好使用numpyscipy 中的矢量化函数重写它。作为最后的手段,你可以使用np.vectorize

import math
def my_custom_func(x):
    return math.log(x)

f = np.vectorize(my_custom_func)
df.assign(log2=lambda x: f(x['value'] / x['reading']))

【讨论】:

  • 感谢您的回答。我还尝试了其他一些基本操作,例如 * 并且遇到了同样的问题。我应该定义一个矢量化乘积函数还是有更好的方法?例如:df.assign(prodc = lambda x: 1 if (x.value * 2 > 4) else 0)
  • x 是 lambda 是一个数据框,所以 x['value'] 是一个系列。您必须使用矢量化函数来处理它们:df.assign(prodc = lambda x: np.where(x['value'] * 2 &gt; 4, 1, 0))
  • 谢谢! @代码不同
猜你喜欢
  • 2012-09-26
  • 1970-01-01
  • 2020-11-15
  • 2019-08-06
  • 2016-05-15
  • 2019-04-10
  • 2012-08-01
  • 1970-01-01
  • 2015-01-25
相关资源
最近更新 更多