Home > Net >  how to change values in a df specifying by index contain in multiple lists, and each list for one co
how to change values in a df specifying by index contain in multiple lists, and each list for one co

Time:11-24

I have a list where I have all the index of values to be replaced. I have to change them in 8 diferent columns with 8 diferent lists. The replacement could be a simple string. How can I do it? I have more than 20 diferent columns in this df

Eg:

list1 = [0,1,2]
list2 =[2,4]
list8 = ...

sustitution = 'no data'

Column A Column B
marcos peter
Julila mike
Fran Ramon
Pedri Gavi
Olmo Torres
OUTPUT: 

| Column A | Column B |
| -------- | -------- |
| no data  | peter    |
| no data  | mike     |
| no data  | no data  |
| Pedri    | Gavi     |
| Olmo     | no data  |`

CodePudding user response:

Use DataFrame.loc with zipped lists and columns names:

list1 = [0,1,2]
list2 =[2,4]

L = [list1,list2]
cols = ['Column A','Column B']

sustitution = 'no data'

for c, i in zip(cols, L):
    df.loc[i, c] = sustitution
print (df)
  Column A Column B
0  no data    peter
1  no data     mike
2  no data  no data
3    Pedri     Gavi
4     Olmo  no data

CodePudding user response:

You can use the underlying numpy array:

list1 = [0,1,2]
list2 = [2,4]

lists = [list1, list2]

col = np.repeat(np.arange(len(lists)), list(map(len, lists)))
# array([0, 0, 0, 1, 1])
row = np.concatenate(lists)
# array([0, 1, 2, 2, 4])

df.values[row, col] = 'no data'

Output:

  Column A Column B
0  no data    peter
1  no data     mike
2  no data  no data
3    Pedri     Gavi
4     Olmo  no data
  • Related