嗨,下面是我的数据集。
我需要根据每个形状来计算体积。如何在不使用太多for循环的情况下应用公式。我有超过8-9个这样的唯一值,我需要在新的派生变量中计算其体积
下面是数据帧
输入:
Type Len wid hig dia
cylinder 165 42
oval 30 38 141
round 131 48
oval 63 95 141
cylinder 120 42输出:
type Len wid hig dia vol
cylinder 165 42 238
oval 30 38 141 632
round 131 48 57
oval 63 95 141 200
cylinder 120 42 173代码:
def label_race (row):
if Anomaly_1['Type'] == 'Cylindrical' :
return (4/3*3.14*(Length/2)*(Width/2)*(Height/2))/1000
if Anomaly_1['Type'] == 'Oval' :
return (pi*(Diameter/2)^2*h)发布于 2019-05-17 14:27:09
您可以使用numpy.select
m1 = Anomaly_1['Type'] == 'cylindrical'
m2 = Anomaly_1['Type'] == 'oval'
m3 = ...
v1 = (4/3*3.14*(Anomaly_1['Len']/2)*(Anomaly_1['wid']/2)*(Anomaly_1['hig']/2))/1000
v2 = (np.pi*(Anomaly_1['dia']/2)**2*Anomaly_1['hig'])
v3 = ...
Anomaly_1['vol'] = np.select([m1, m2, m3], [v1, v2, v3])另一种具有自定义函数的解决方案,用于单独处理值:
def f(x):
if x['Type'] == 'cylindrical':
return (4/3*3.14*(x['Len']/2)*(x['wid']/2)*(x['hig']/2))/1000
elif x['Type'] == 'oval':
return (np.pi*(x['dia']/2)**2*x['hig'])
Anomaly_1['vol'] = Anomaly_1.apply(f, axis=1)发布于 2019-05-17 14:26:08
您可以使用pd.Dataframe.apply()方法在单个操作中完成此操作。它可以创建一个名为"Vol“的新列,该列是函数的结果。
在这种情况下,您的函数可能如下所示:
def volume(shape: str = '', len: int = 1 , wid: int = 1, hig: int = 1 dia: int = 1) -> int:
if shape == 'cylinder':
vol = formula
elif shape == 'oval':
vol = other formula
elif shape == 'cylinder':
vol = other other formula
return volhttps://stackoverflow.com/questions/56180610
复制相似问题