Changing columns for each row in a data frame based on another column

I have a dataframe that has many columns. I want to apply a function to each row that modifies all columns based on different columns.

def mark(row):
  columns = get_columns_to_alter(row['Text'])
  for c in columns:
      row[c] = True

And I tried to use the apply function

 df.apply(mark, axis=1)

But this does not change these columns. What am I doing wrong? The function I gave is psuedocode, but it gets the column names to change based on the Text column.

+4
source share
2 answers

OK, to be honest, this is a bit confusing. A few problems that I see:

First , the DataFrame.applyfunction for each column should look larger:

df.apply(lambda x: mark(x), axis=1)

so that you actually scroll through each line.

, DataFrame.apply ( ); , df, row. df, (a) , mark - (b), - :

def mark(row):
  columns = get_columns_to_alter(row['Text'])
  if len(columns) > 0:
    row[columns] = True
  return row

new_df = df.apply(lambda x: mark(x), axis=1)

- , .

+1

numpy itertools.chain. , .

from itertools import chain
import numpy as np

df = pd.DataFrame(np.random.randint(0, 9, (10, 10)))
df['cols'] = [np.random.randint(0, 9, 3) for _ in df]

def calc_cols(s):

    arr = s.values.tolist()

    # apply function on arr here, e.g.
    # arr = list(map(f, arr))

    idx = np.repeat(list(range(len(arr))), list(map(len, arr)))

    return idx, list(chain(*arr))

A, cols = df.values, calc_cols(df['cols'])

A[cols[0], cols[1]] = -1

df_res = pd.DataFrame(A, columns=df.columns)

#     0   1   2   3   4   5   6   7   8  9       cols
# 0   2   4  -1   4  -1   2   6   6   8  1  [4, 4, 2]
# 1   4  -1  -1   3   4   4  -1   5   6  7  [2, 1, 6]
# 2  -1   1   7   1   2  -1   2   2  -1  0  [8, 0, 5]
# 3   2   4  -1   6  -1   8   6  -1   0  3  [7, 2, 4]
# 4  -1   5   5   2   8   2  -1   8  -1  6  [8, 6, 0]
# 5   5   6   0   3   5  -1  -1   5   3  7  [6, 5, 6]
# 6  -1   0   7   1   4  -1  -1   6   1  8  [5, 6, 0]
# 7   2   6   4   6  -1   6  -1   5   7  6  [6, 4, 6]
# 8  -1   8   1  -1   0   7   8  -1   2  3  [3, 0, 7]
# 9   2   4   6   6  -1  -1   0   2  -1  0  [4, 8, 5]
0

Source: https://habr.com/ru/post/1694683/


All Articles