我知道你的问题特别要求一个将数据帧作为参数的函数,但我觉得你的方法破坏了数据帧的强度。我会选择直接转型方法
import pandas as pd
df = pd.read_csv('your_data_source.csv')
Function output in a new column fn_A
df['fn_A'] = df[df['A'].apply(lambda x: x < 125)]['A'].apply(lambda y: 935 + 0.2 * y)
df['fn_A'] = df[df['A'].apply(lambda x: 955 < x < 974)]['A'].apply(lambda y: 921.2 + 0.2 * (y - 955))
df['fn_A'] = df[df['A'].apply(lambda x: 975 < x < 1023)]['BCCH'].apply(lambda y: 925.2 + 0.2 * (y - 975))
df['fn_A'] = df[df['A'].apply(lambda x: 511 < x < 885)]['A'].apply(lambda y: 1805.2 + 0.2 * (y - 512))
您可以利用它np.select来管理您的条件和选项。这使您可以轻松地维护您的条件和选项,并使用numpy库函数,这可能有助于加快您的代码
def fn(dframe):
import numpy as np
condlist = [
dframe['A'] < 125,
(dframe['A'] >= 955) and (dframe['A'] <= 974),
(dframe['A'] >= 975) and (dframe['A'] <= 1023),
(dframe['A'] >= 511) and (dframe['A'] <= 885),
]
choicelist = [
935 + 0.2 * dframe['A'],
921.2 + 0.2 * (dframe['A'] - 955),
925.2 + 0.2 * (dframe['BCCH'] - 975),
1805.2 + 0.2 * (dframe['A'] - 512),
]
output = np.select(condlist,choicelist)
return output
看来你需要np.where
import numpy as np
np.where(dframe['A'] < 125, 935 + 0.2 * dframe['A'],
np.where(dframe['A'] >= 511) & (dframe['A'] <= 885), 1805.2 + 0.2 * (dframe['A'] - 512,
np.where(dframe['A'] <= 974, 921.2 + 0.2 * (dframe['A'] - 955),
np.where(dframe['A'] <= 1023, 925.2 + 0.2 * (dframe['A'] - 975),
'Value for any other value'))))