Meh*_*are 0 python dataframe python-3.x pandas
基于具有列值函数的 Sort pandas DataFrame
我想使用log()该方法应用一个函数,例如数据框.assign(),以创建临时列并将其用作排序标准,但是,我无法像该方法的工作方式那样传递轴参数.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)]})
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我不能像这样使用 .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'>
Run Code Online (Sandbox Code Playgroud)
或者
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'>
Run Code Online (Sandbox Code Playgroud)
但它与 .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
Run Code Online (Sandbox Code Playgroud)
有什么解决方法可以使用分配或其他方法将其用作排序中的临时列吗?
apply(..., axis=1)当您必须逐行执行操作时,您应该尽可能多地使用向量化函数,并将其作为最后的手段。
np.log您的问题可以通过向量化来解决:
df.assign(log=lambda x: np.log(x['value'] / x['reading']))
Run Code Online (Sandbox Code Playgroud)
如果您有自定义函数,最好使用numpy或 中的矢量化函数重写它scipy。作为最后的手段,您可以使用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']))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2180 次 |
| 最近记录: |