Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为当前列中的每个值派生变量_Python_Python 3.x_Pandas_Dataframe_Group By - Fatal编程技术网

Python 如何为当前列中的每个值派生变量

Python 如何为当前列中的每个值派生变量,python,python-3.x,pandas,dataframe,group-by,Python,Python 3.x,Pandas,Dataframe,Group By,下面是我的数据集 我需要根据每个形状计算体积。如何应用公式而不使用太多for循环。我有超过8-9个这样的唯一值,我需要计算新派生变量中的体积 下面是tha数据帧 输入: Type Len wid hig dia cylinder 165 42 oval 30 38 141 round

下面是我的数据集

我需要根据每个形状计算体积。如何应用公式而不使用太多for循环。我有超过8-9个这样的唯一值,我需要计算新派生变量中的体积

下面是tha数据帧

输入:

  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
代码:


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

另一个具有单独处理值的自定义函数的解决方案:

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)
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)