0

Look at the following code:

import numpy as np
import pandas as pd

np.random.seed(42)
arr = np.random.randint(1, 11, (5, 5)).astype(np.float)
df = pd.DataFrame(arr)

>>> df
Out[49]: 
      0    1     2    3    4
0   7.0  4.0   8.0  5.0  7.0
1  10.0  3.0   7.0  8.0  5.0
2   4.0  8.0   8.0  3.0  6.0
3   5.0  2.0   8.0  6.0  2.0
4   5.0  1.0  10.0  6.0  9.0

rows, cols = [0, 2], [1, 3]
arr[rows, cols] = np.nan
df = pd.DataFrame(arr)

>>> df
Out[50]: 
      0    1     2    3    4
0   7.0  NaN   8.0  5.0  7.0
1  10.0  3.0   7.0  8.0  5.0
2   4.0  8.0   8.0  NaN  6.0
3   5.0  2.0   8.0  6.0  2.0
4   5.0  1.0  10.0  6.0  9.0

Is there a way to replace the values at the defined indices with e.g. NaN that does not require the conversion of the dataframe to a numpy array?

2
  • Are you only interested in replacing nan values? This post will should be useful if so. Commented Jan 30, 2019 at 18:45
  • Thanks for the response! No Im interested in a numpy-like replacement using the indices of rows & columns (not index and column names, but the numerical indices) Commented Jan 30, 2019 at 19:25

2 Answers 2

1

Try this:

df.values[rows, cols]
Sign up to request clarification or add additional context in comments.

2 Comments

values will actually give a numpy array.
This is the shortcut I have searched for. df.values outputs an numpy array, but df.values[rows, cols] = np.nan updates the dataframe! This allows me to replace values in the dataframe by using numerical indices (that is I don't have to care about the labeling of the rows/columns of the dataframe)
0

Using lookup

df.lookup(rows,cols)
Out[810]: array([4, 3])

3 Comments

This is essentially doing the same things as in my answer, or iterating over the indices using zip() and getting each value at a time
@Colonder not always same , this one is index and columns base, .values is position base , so close but not same .
Thanks for the reply. I edited the question a little bit. @Colonder indeed came up with what I was looking for

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.