Python 3.x 函数是慢的,可选np。其中';s格式对用户/读者不友好
我有以下数据集Python 3.x 函数是慢的,可选np。其中';s格式对用户/读者不友好,python-3.x,pandas,function,numpy,Python 3.x,Pandas,Function,Numpy,我有以下数据集 ORIGINFACILITYCODE object ZIP5 object total_edd float64 final_edd float64 D1 float64 D2 float64 D3 float
ORIGINFACILITYCODE object
ZIP5 object
total_edd float64
final_edd float64
D1 float64
D2 float64
D3 float64
D4 float64
D5 float64
D6 float64
D7 float64
D8 float64
D9 float64
D10 float64
D11 float64
D12 float64
D13 float64
我想根据另一列中的值返回特定的列值
因此,我创建了以下函数
def edd_cal_func(x,EDD_TYPE):
if x[EDD_TYPE]==1:
return pd.Series(x['D1'])
elif x[EDD_TYPE]==2:
return pd.Series(x['D2'])
elif x[EDD_TYPE]==3:
return pd.Series(x['D3'])
elif x[EDD_TYPE]==4:
return pd.Series(x['D4'])
elif x[EDD_TYPE]==5:
return pd.Series(x['D5'])
elif x[EDD_TYPE]==6:
return pd.Series(x['D6'])
elif x[EDD_TYPE]==7:
return pd.Series(x['D7'])
elif x[EDD_TYPE]==8:
return pd.Series(x['D8'])
elif x[EDD_TYPE]==9:
return pd.Series(x['D9'])
elif x[EDD_TYPE]==10:
return pd.Series(x['D10'])
elif x[EDD_TYPE]==11:
return pd.Series(x['D11'])
elif x[EDD_TYPE]==12:
return pd.Series(x['D12'])
elif x[EDD_TYPE]==13:
return pd.Series(x['D13'])
但是,运行时间为5分钟。(文件包括大约100万行)
我知道使用np.where会更有效、更快
w25_27_test['total_edd_test'] = np.where(w25_27_test['total_edd']==1,
w25_27_test['D1'],
np.where(w25_27_test['total_edd']==2,
w25_27_test['D2'],
np.where(w25_27_test['total_edd']==3,
w25_27_test['D3'],
np.where(w25_27_test['total_edd']==4,
w25_27_test['D4'],
np.where(w25_27_test['total_edd']==5,
w25_27_test['D5'],
np.where(w25_27_test['total_edd']==6,
w25_27_test['D6'],
np.where(w25_27_test['total_edd']==7,
w25_27_test['D7'],
np.where(w25_27_test['total_edd']==8,
w25_27_test['D8'],
np.where(w25_27_test['total_edd']==9,
w25_27_test['D9'],
np.where(w25_27_test['total_edd']==10,
w25_27_test['D10'],
np.where(w25_27_test['total_edd']==11,
w25_27_test['D11'],
np.where(w25_27_test['total_edd']==12,
w25_27_test['D12'],
np.where(w25_27_test['total_edd']==13,
w25_27_test['D13'],
-1)))))))))))))
但是,它不会像前面的函数那样对读者友好/可伸缩(EDD_类型可以是可变的)。有没有更好的方法来修正这一点。
(如何将np.where包装为函数?这看起来非常混乱,我不确定我是否理解您的问题 但是,IIUC用于循环和
np。选择
cond = [df['total_edd'] == i for i in range(1, 4)]
choice = [df[f'D{i}'] for i in range(1, 4)]
np.select(cond, choice, -1)
这看起来真的很混乱,我不确定我是否理解你的问题
但是,IIUC用于循环和np。选择
cond = [df['total_edd'] == i for i in range(1, 4)]
choice = [df[f'D{i}'] for i in range(1, 4)]
np.select(cond, choice, -1)
这对我的案子有效。然而,我并没有真正理解。请你再解释一下好吗。条件/选项是列表的列表。这将只返回一个列表。是广播吗?对我的案子有效。然而,我并没有真正理解。请你再解释一下好吗。条件/选项是列表的列表。这将只返回一个列表。广播吗?