Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.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 将函数应用于数据帧';s指数_Python_Pandas_Dataframe - Fatal编程技术网

Python 将函数应用于数据帧';s指数

Python 将函数应用于数据帧';s指数,python,pandas,dataframe,Python,Pandas,Dataframe,我需要创建一个函数,该函数接收一个数字X,然后在X行中划分两个特定列。然后我需要制作一整列(使用我的函数和apply)来显示这两列的商。如何将函数应用于数据帧索引并使其成为列? 以下是我的功能: def ratio(x): Length = df2.iloc[x]['Sepal.Length'] Width = df2.iloc[x]['Sepal.Width'] return Length/Width 如果我正确理解了您的问题,您希望基于其他

我需要创建一个函数,该函数接收一个数字
X
,然后在
X
行中划分两个特定列。然后我需要制作一整列(使用我的函数和apply)来显示这两列的商。如何将函数应用于数据帧索引并使其成为列? 以下是我的功能:

    def ratio(x):
       Length = df2.iloc[x]['Sepal.Length']
       Width = df2.iloc[x]['Sepal.Width']
       return Length/Width

如果我正确理解了您的问题,您希望基于其他两列创建一个
比率
列,您只需执行此操作,它将创建一个新列,而无需迭代所有行:

df2['ratio'] = df2['Sepal.Length'] / df2['Sepal.Width']
如果您仍然希望使用函数并应用它,您可以使用。您还需要根据
apply
更改函数,因为它将参数作为整行:

def ratio(row):
  Length = row['Sepal.Length']
  Width = row['Sepal.Width']
  return Length/Width

df2['ratio'] = df2.apply(ratio, axis = 1)

是的,这正是我想要做的,但我需要用函数来做…请检查在函数的长度行上写下这行“invalid literal for int(),base 10:'setosa'”后弹出的编辑器eror,为什么?我已经根据
apply
的工作方式对函数做了一些更改,现在应该可以正常工作了。