1

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  |`

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer but appears: ValueError: too many values to unpack (expected 2)
@DEA - It was copy error, need for c, i in zip(df.columns, L): instead for c, i in L
Thanks, now is executing without error, but do not change values properly. Notice that df have more than 8 columns but I only want to change this specific 8
@DEA - I change solution by this requirement, you can check it here
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.