我正在使用 python 3.X。我正在尝试使用eval() https://pandas.pydata.org/pandas-docs/stable/generated/pandas.eval.html#pandas.eval数据框方法,包括这样的自定义函数
import pandas as pd
import numpy as np
df = pd.DataFrame({
'T': [0, 10, 0, 10, 10, 30],
'P': [0, 0, 1000, 1000, 0, 0],
'S': [25, 25, 25, 25, 40, 40]
})
def custom(A, B, C):
# some operations
aux = pd.DataFrame({
'A': [0, 10, 0, 10, 10, 30],
})
return aux.A # here is where I want to return the numpy array or list, or dataframe column
eq = 'RES = T + @custom(S, T, P) + 2'
df.eval(eq, engine='numexpr', inplace=True)
但我只能在函数中返回一个浮点或整数值,一个简单的值。
所以我想返回一个 numpy 数组或值列表,因为我想使用结果来操作方程变量的其余部分。我收到此错误:
TypeError: unhashable type: 'numpy.ndarray'
另一个例子:
import pandas as pd
import numpy as np
import seawater as sw
from seawater.library import T90conv
df = pd.DataFrame({
'T': T90conv([0, 10, 0, 10, 10, 30]),
'P': [0, 0, 1000, 1000, 0, 0],
'S': [25, 25, 25, 25, 40, 40]
})
cndr = sw.cndr # it returns a numpy array
eq = 'NEW = @cndr(S, T, P)'
df.eval(eq, engine='numexpr', inplace=True)
那可能吗?我可以返回哪些类型?还有其他方法可以实现这一目标吗?