首页 > 解决方案 > 如何使用应用于数据框迭代行?

问题描述

我想使用 apply 方法迭代行。第一行“1”是一个带有句子的字符串,其余行是浮点数。我将把这些行用在一个函数中。像这样的东西:

def my_function(row1, row2, row3, row4):
  if row["1"]:
    '''do some stuff here with the rows'''
  return # the dataframe with the modification to the float rows "2" "3" "4" 

df['row1'] = df['row1'].apply(lambda row: my_function(row['row1'], row['row2'], row['row3'], row['row4']))

TypeError: string indices must be integers

一个例子:第一行是一个句子,如果句子中有任何“a”,那么我们继续修改浮点行,函数将返回最后三行的修改。

标签: pythonpandas

解决方案


您需要声明轴,因为默认情况下apply沿列应用函数。另一方面,你应该决定你的函数是使用一行作为参数还是单个元素,老实说我更喜欢第一个。你的代码可能是这样的:你需要这个:

def my_function(row):
  if row["a"] ... :
    # do something
  if row["b"] ... :
    # do something
  return something

df_negative['new_a'] = df_negative['a'].apply(my_function, axis=1)  # without lambda function

推荐阅读