gpt4 book ai didi

python - 如何为列中存在的每个值导出变量

转载 作者:行者123 更新时间:2023-12-01 00:56:47 29 4
gpt4 key购买 nike

您好,下面是我的数据集。

我需要根据每个形状计算体积。我如何应用公式而不使用太多 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)

最佳答案

您可以使用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)

关于python - 如何为列中存在的每个值导出变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56180610/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com