【发布时间】: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 或其他方法将其用作排序中的临时列?
【问题讨论】:
-
你从哪里得到
log?np.log对我有用。 -
来自数学导入日志
-
math.log将期望一个标量实体——即单个float。使用numpy.log,因为它适用于任何支持数组接口(包括熊猫系列)的东西 -
我也有一些自定义函数有同样的问题,都是关于传递axis=1参数的。
-
感谢@mgilson,解决了部分问题!
标签: python python-3.x pandas dataframe