简体   繁体   中英

How to iterate over rows using apply to a dataframe?

I would like to iterate over rows using the apply method. The first row "1" is a string with sentence, the rest of the rows are floats. I will take this rows to use it into a function. Something like this:

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

An example: the first row is a sentence and if has any "a" in the sentence, then we proceed to modify the float rows, and the function will return the modification of this three last rows.

You need to declare the axis, for default apply applies a function along columns. On the other hand, you should decide if your function is going to use a row as argument or single elements, to be honest I prefer the first one. Your code could be something like this: You need this one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM